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

本文說明如何將色彩新增至自訂視覺效果,以及如何處理已定義色彩之視覺效果的資料點。

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

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

將色彩新增至資料點

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

/**
 * 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 會管理視覺效果中使用的色彩。 服務實例 colorPalette 可在 上使用 IVisualHost

使用下列程式碼在 方法中 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,
        });
    }
}

然後,將資料從 dataPoints 套用至 方法內的 update d3 選取 barSelection 範圍:

// 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();