이 문서에서는 사용자 지정 시각적 개체에 색을 추가하는 방법과 정의된 색이 있는 시각적 개체의 데이터 요소를 처리하는 방법을 설명합니다.
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 메서드는 막대형 차트 뷰모델의 일부입니다. 계산을 모두 반복하는 visualTransform 메서드는 색을 할당하기에 최적의 장소입니다. 다음 코드와 같이 사용할 수 있습니다.
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,
});
}
}
그런 다음, 메서드 내의 d3 선택 barSelection 영역에 데이터를 dataPoints 적용합니다update.
// 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();