次の方法で共有


Power BI ビジュアルに色を追加する

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

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

ビジュアルの作成を開始するには、「 Power BI Circle Card ビジュアルの開発」を参照してください。

データ ポイントに色を追加する

各データ ポイントを異なる色で表すには、次の例に示すように、 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,
        });
    }
}

次に、update メソッド内の d3 選択barSelectiondataPointsのデータを適用します。

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