为 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 服务管理视觉对象中使用的颜色。 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();

后续步骤