【发布时间】:2020-05-07 22:50:54
【问题描述】:
我正在创建一个高位图表图形,我想根据对象的标题动态地赋予图形颜色。我目前有一个数组graphData,它有一个对象title。
我有 5 种可能的标题结果:
"LOW", "MEDIUM-LOW", "MEDIUM", "MEDIUM-HIGH", AND "HIGH"
我现在尝试遍历我的数组并根据索引的标题分配颜色。
我的整个图表根据数组的最后一个标题接收一种颜色。我希望颜色能够单独影响数组的每个索引。
例如:如果“MEDIUM-HIGH”是数组中的最后一个标题,我的整个图表将获得#DD5F0C
这是我的代码:
数组:
graphData: [ […]
0: Object { title: "LOW", result: 62582 }
1: Object { title: "MEDIUM-LOW", result: 57758 }
2: Object { title: "LOW", result: 8795 }
3: Object { title: "HIGH", result: 262525 }
4: Object { title: "MEDIUM-HIGH", result: 167168 } ]
let graphColor = ""
for (i = 0; i < graphData.length; i++) {
if (graphData[i].title === "LOW") {
graphColor = "#0D6302"
} else if (graphData[i].title === "MEDIUM-LOW") {
graphColor = "#0B7070"
} else if (graphData[i].title === "MEDIUM") {
graphColor = "#DC9603"
} else if (graphData[i].title === "MEDIUM-HIGH") {
graphColor = "#DD5F0C"
} else if (graphData[i].title === "HIGH") {
graphColor = "#C50710"
}
}
HighCharts 代码:
Highcharts.chart('container', {
chart: {
type: 'bar'
},
title: {
text: "Bar Graph"
},
xAxis: {
},
yAxis: {
min: 0,
formatter: function() {
return this.value + "%";
},
title: {
text: '% of Total'
}
},
legend: {
reversed: false
},
plotOptions: {
series: {
stacking: 'normal'
}
},
series: [{
name: `graphData[0].title`,
color: graphColor,
data: [graphData[0]],
}, {
name: 'graphData[1].title',
color: graphColor,
data: [graphData[1]],
showInLegend: false,
linkedTo: ":previous"
}, {
name: 'graphData[2].title,
color: graphData[0].title,
data: [graphData[2]]
}, {
name: graphData[3].title,
color: '#DC9603',
data: [graphData[3]]
}, {
name: graphData[4].title,
color: graphColor,
data: [graphData[4]]
}, {
name: graphData[5].title,
color: graphColor,
data: [graphData[5]]
}]
});
我希望我的“颜色”能够根据 graphData.title 对应的特定索引动态生成。
【问题讨论】:
-
在您的第一个代码块中,您在第一次检查时访问
.title,然后在第二次、第三次访问时访问.Title(大写),依此类推。它们是不等价的。 -
我很抱歉,这是我的错字,除了
.title小写。 -
return 将在第一次迭代时退出 真的不清楚你期望发生什么......
-
在
graphData[i].color中设置颜色,这样每个数据元素都有不同的颜色。不要从 for 循环中返回颜色,因为这会在第一次迭代后停止。然后在series中使用color: graphData[3].color(例如)。 -
@espascrello 我稍微编辑了我的问题,希望能澄清我遇到的问题。我正在遍历整个数组并尝试根据索引中的标题为每个单独的索引签名。例如,
index: 0 === "LOW"我图表上的这个索引将显示#0D6302,下一个索引 1 === "HIGH" 这个索引的数据将返回 "#C50710" 等等
标签: javascript arrays loops highcharts