Power BI ビジュアルへの色の追加

この記事では、カスタム ビジュアルに色を追加する方法と、色を定義したビジュアルのデータ ポイントを処理する方法について説明します。

IVisualHost は、視覚エフェクトのホストと対話するプロパティとサービスのコレクションであり、colorPalette サービスでカスタム視覚エフェクトの色を定義できます。 この記事のサンプル コードでは、SampleBarChart ビジュアルを変更します。 SampleBarChart 視覚エフェクトのソース コードについては、barChart.ts をご覧ください。

視覚化の作成を始めるには、Power BI の円形カード視覚化の開発に関する記事を参照してください。

データ ポイントへの色の追加

各データ ポイントを異なる色で表すには、次の例に示すように、BarChartDataPoint インターフェイスに color 変数を追加します。

/**
 * 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 メソッドは、横棒グラフ ViewModel の一部です。 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 メソッド内で dataPoints からのデータを d3-selection 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();

次の手順