共用方式為


將色彩新增至您的 Power BI 視覺效果

此文章會說明如何將色彩新增至您的自訂視覺效果,以及如何處理具有定義色彩之視覺效果的資料點。

IVisualHost,與視覺主機互動的屬性和服務集合,可以使用 colorPalette 服務定義自訂視覺效果中的色彩。 此文章中的範例程式碼會修改 SampleBarChart 視覺效果 \(英文\)。 如需 SampleBarChart 視覺效果原始程式碼,請參閱 barChart.ts

若要開始建立視覺效果,請參閱開發 Power BI 圓形卡片視覺效果

將色彩新增至資料點

若要以不同色彩表示每個資料點,請將 color 變數新增至 BarChartDataPoint 介面,如下列範例所示:

/**
 * Interface for BarChart data points.
 *
 * @interface
 * @property {number} value    - Data value for point.
 * @property {string} category - Corresponding category of data value.
 * @property {string} color    - Color corresponding to data point.
 */
interface BarChartDataPoint {
    value: number;
    category: string;
    color: string;
};

使用調色盤服務

colorPalette 服務會管理視覺效果中所使用的色彩。 IVisualHost 提供 colorPalette 服務的執行個體。

使用下列程式碼在 update 方法中定義調色盤:

constructor(options: VisualConstructorOptions) {
        this.host = options.host; // host: IVisualHost
        ...
    }

public update(options: VisualUpdateOptions) {

    let colorPalette: IColorPalette = host.colorPalette;
    ...
}

將色彩指派給資料點

接下來,指定 dataPoints。 在此範例中,每個 dataPoints 都有定義的值、類別與色彩屬性。 dataPoints 也可以包含其他屬性。

SampleBarChart中,visualTransform 方法是 [橫條圖] 檢視模型的一部分。 因為 visualTransform 方法會逐一查看所有 dataPoints 計算,所以這是指派色彩的理想位置,如下列程式碼所示:


public update(options: VisualUpdateOptions) {
    ....
    let viewModel: BarChartViewModel = visualTransform(options, this.host);
    ....
}

function visualTransform(options: VisualUpdateOptions, host: IVisualHost): BarChartViewModel {
    let colorPalette: IColorPalette = host.colorPalette; // host: IVisualHost
    for (let i = 0, len = Math.max(category.values.length, dataValue.values.length); i < len; i++) {
        barChartDataPoints.push({
            category: category.values[i],
            value: dataValue.values[i],
            color: colorPalette.getColor(category.values[i]).value,
        });
    }
}

然後,在 update 方法內的 d3 選取項目 barSelection 上套用來自 dataPoints 的資料:

// This code is for d3 v5
// in d3 v5 for this case we should use merge() after enter() and apply changes on barSelectionMerged
this.barSelection = this.barContainer
    .selectAll('.bar')
    .data(this.barDataPoints);

const barSelectionMerged = this.barSelection
    .enter()
    .append('rect')
    .merge(<any>this.barSelection);

barSelectionMerged.classed('bar', true);

barSelectionMerged
.attr("width", xScale.bandwidth())
.attr("height", d => height - yScale(<number>d.value))
.attr("y", d => yScale(<number>d.value))
.attr("x", d => xScale(d.category))
.style("fill", (dataPoint: BarChartDataPoint) => dataPoint.color)
.style("stroke", (dataPoint: BarChartDataPoint) => dataPoint.strokeColor)
.style("stroke-width", (dataPoint: BarChartDataPoint) => `${dataPoint.strokeWidth}px`);

this.barSelection
    .exit()
    .remove();