【发布时间】:2020-05-28 03:26:36
【问题描述】:
我正在尝试创建一个折线图,其中线条(和点)的颜色取决于所绘制的值。例如,如果该值高于以下阈值[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 中。
如何修改线条本身的颜色?
【问题讨论】:
-
真的很想获得奖金,但是,这能回答你的问题吗? stackoverflow.com/questions/56429021/…
-
@keikai:评论不接受赏金。请对所有问题做出规范的回答以回答部分。
-
@mico 确定我知道指南,只是注意到重复的内容感觉更好,而不是答案。
-
真的很抱歉没有回应......我被感染了一个人流感!正如@mico 评论,要分配赏金,我需要一个有效的答案@keikai,如果你能提供一个,我会非常乐意分配赏金:)
标签: javascript charts chartjs-2.6.0 react-chartjs