Front/JS & jQuery
[js][Echarts] stack bar 차트에서 각 막대에 다른 색상 설정하기
오선지♬
2024. 12. 26. 20:59
728x90
반응형
ECharts에서 x축을 따라 막대형 차트의 각 막대에 다른 색상을 설정하려면,
각 막대에 해당하는 배열을 사용하여 개체 itemStyle내의 속성을 사용자 지정할 수 있습니다.
getCoChartOption = (xAxisData, amtArr, otherArr, valRange) => {
const amtColors = ["#F4E5E0", "#F0A5A0", "#E8C6C0", "#D8B7A0"]; // Example colors for "영업수익" bars
const otherColors = ["#5FC6E3", "#4BADD8", "#3A95B3", "#2681A0"]; // Example colors for "영업외수익" bars
return {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
legend: {},
grid: {
top: "10%",
bottom: "10%",
left: "10%",
right: "10%"
},
xAxis: {
type: 'category',
data: xAxisData,
},
yAxis: [
{
type: 'value',
show: false,
min: valRange[0],
max: valRange[1]
}
],
series: [
{
name: '영업수익',
data: amtArr,
type: 'bar',
stack: 'Ad',
barWidth: '30%',
itemStyle: {
color: (params) => {
return amtColors[params.dataIndex % amtColors.length]; // Set different color for each bar
}
},
label: {
show: true,
fontSize: 12,
position: "top",
align: "right",
color: "black",
formatter: function(data) {
data = Common.numberWithCommas(data.data);
return data;
}
}
},
{
name: '영업외수익',
data: otherArr,
type: 'bar',
stack: 'Ad',
barWidth: '25%',
itemStyle: {
color: (params) => {
return otherColors[params.dataIndex % otherColors.length]; // Set different color for each bar
}
},
label: {
show: true,
fontSize: 12,
fontWeight: "bold",
position: "top",
align: "left",
color: "black",
formatter: function(data) {
data = Common.numberWithCommas(data.data);
return data;
}
}
}
]
}
}
이 표현식은 막대 차트의 현재 데이터 포인트 인덱스를 기반으로 배열 amtColors[params.dataIndex % amtColors.length]에서 색상을 선택하는 데 사용됩니다 . 이 표현식의 각 부분에 대한 세부 내용은 다음과 같습니다.amtColors
- params.dataIndex:
- 이것은 차트에서 현재 데이터 포인트(또는 막대)의 인덱스입니다. 즉, 시리즈에서 현재 막대의 위치(예: 첫 번째 막대, 두 번째 막대 등)를 알려줍니다.
- amtColors.length:
- 이것은 배열의 길이입니다 amtColors. amtColors배열에 4가지 색상이 있으면 amtColors.length4가 됩니다.
- params.dataIndex % amtColors.length:
- 이것은 모듈로 연산자( %)로, 를 나누어 params.dataIndex나머지 amtColors.length를 반환합니다. 나머지는 항상 0과 사이의 정수입니다 amtColors.length - 1.
- 예를 들어:
- params.dataIndex0이면 첫 0 % 4 = 0번째 색상( amtColors[0])이 사용됩니다.
- params.dataIndex가 1 이면 1 % 4 = 1두 번째 색상( amtColors[1])이 사용됩니다.
- 만약 params.dataIndex4라면 , 첫 번째 색상( ) 4 % 4 = 0으로 다시 루프됩니다 .amtColors[0]
- amtColors[...]:
- 이것은 배열에서 색상에 접근하는 데 사용됩니다 amtColors. 모듈로 결과에 따라 배열에서 특정 색상이 선택됩니다.
예:
amtColors = ["#F4E5E0", "#F0A5A0", "#E8C6C0", "#D8B7A0"], 막대가 6개(0~5)인 경우 params.dataIndex색상은 다음과 같이 적용됩니다.
- 의 경우 params.dataIndex = 0색상은 다음과 같습니다 amtColors[0] = "#F4E5E0".
- 의 경우 params.dataIndex = 1색상은 다음과 같습니다 amtColors[1] = "#F0A5A0".
- 의 경우 params.dataIndex = 2색상은 다음과 같습니다 amtColors[2] = "#E8C6C0".
- 의 경우 params.dataIndex = 3색상은 다음과 같습니다 amtColors[3] = "#D8B7A0".
- 의 경우 params.dataIndex = 4색상은 로 다시 돌아갑니다 amtColors[0] = "#F4E5E0".
- 의 경우 params.dataIndex = 5색상은 다음과 같습니다 amtColors[1] = "#F0A5A0".
이렇게 하면 필요에 따라 색상이 순환되어 각 막대가 뚜렷한 색상을 갖게 됩니다.
728x90
반응형