我正在尝试创建折线图,其中线(和点)的颜色取决于所绘制的值。例如,如果该值高于以下阈值[0, 115, 125]
,则颜色将分别为['green', 'yellow', 'red']
。
该要求与本示例中实现的要求几乎相同:https://jsfiddle.net/egamegadrive16/zjdwr4fh/
区别在于我使用的是react-chart-js-2
,因此,无法以相同的方式访问draw()
方法。相反,建议创建一个插件来操纵图表。
这是目前的插件代码:
import { Chart } from "react-chartjs-2";
class variableLineColorUtils {
selectColor(value, thresholds, colors) {
let color = colors[0];
thresholds.every((limit, index) => {
if (value < limit) return false;
else color = colors[index];
return true;
});
return color;
}
}
const variableLineColor = {
id: "variableLineColor",
afterDraw: (chart, easing) => {
const options = chart.options.variableLineColor;
if (options) {
const utils = new variableLineColorUtils();
const datasets = chart.config.data.datasets;
datasets.forEach((set, i) => {
const points = chart.getDatasetMeta(i).data;
points.forEach((point, index) => {
const color = utils.selectColor(
datasets[i].data[point._index],
options.thresholds,
options.colors
);
point.custom = { borderColor: color, backgroundColor: color };
});
chart.update();
});
}
}
};
Chart.pluginService.register(variableLineColor);
export default variableLineColor;
这些是用于插件的
options
:variableLineColor: {
thresholds: [0, 115, 125],
colors: ["green", "yellow", "red"]
}
此方法仅修改点本身的颜色,而不修改点之间的线。该行保留在图表的默认
backgroundColor
中。如何修改线条本身的颜色?
最佳答案
尝试使用borderColor代替backgroundColor,请引用ChartJs StackOverflow。它可以解决您的问题。
关于javascript - Chart JS插件根据值更改线条颜色,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60190586/