She*_*ixt 7 javascript charts react-chartjs chartjs-2.6.0
我正在尝试创建一个折线图,其中线条(和点)的颜色取决于绘制的值。例如,如果该值高于以下阈值,[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;
Run Code Online (Sandbox Code Playgroud)
这些是options
用于插件的:
variableLineColor: {
thresholds: [0, 115, 125],
colors: ["green", "yellow", "red"]
}
Run Code Online (Sandbox Code Playgroud)
这种方法只修改点本身的颜色,而不是点之间的线。该线保留在图表的默认值中backgroundColor
。
如何修改线条本身的颜色?
您可以使用该plugins
数组创建一个新beforeRender
插件来完成此任务。
plugins: [{
beforeRender: (x, options) => {
const c = x.chart;
const dataset = x.data.datasets[0];
const yScale = x.scales['y-axis-0'];
const yPos = yScale.getPixelForValue(0);
const gradientFill = c.ctx.createLinearGradient(0, 0, 0, c.height);
gradientFill.addColorStop(0, 'rgb(86,188,77)');
gradientFill.addColorStop(yPos / c.height, 'rgb(86,188,77)');
gradientFill.addColorStop(yPos / c.height, 'rgb(229,66,66)');
gradientFill.addColorStop(1, 'rgb(229,66,66)');
const model = x.data.datasets[0]._meta[Object.keys(dataset._meta)[0]].dataset._model;
model.borderColor = gradientFill;
},
}];
Run Code Online (Sandbox Code Playgroud)
结果看起来像这样:
model.borderColor
只需将行更改为 ,这也适用于背景颜色model.backgroundColor
。例如:
归档时间: |
|
查看次数: |
3833 次 |
最近记录: |