我想要一个带有react和chart.js和react-chartjs-2的水平条形图,例如当数据发生变化时,该图表应分为两部分黄色和红色。像这个图片 但问题是它显示所有图表为红色, 你可以看到我的完整代码
这是我的条形图组件:
import React, { useEffect, useState } from "react";
import Chart from "chart.js/auto";
import { Bar } from "react-chartjs-2";
import "./BarChart.css";
const BarChart = (props) => {
const [Chartdata, setData] = useState(null);
useEffect(() => {
console.log(props);
setData({
labels: props.labels,
datasets: [
{
label: props.globalLabel,
data: props.data,
backgroundColor: (context) => {
const { ctx, chartArea, scales } = context.chart;
if (!chartArea || !props.colorData) return null;
const { top, bottom, left, right } = chartArea;
const { x, y } = scales;
let gradients = [];
const colorDataLength = props.colorData.length;
if (colorDataLength !== props.data.length) return null;
for (let i = 0; i < colorDataLength; i++) {
const gradientSegment = ctx.createLinearGradient(
0,
left,
0,
right
);
gradientSegment.addColorStop(0, props.colorData[i][0].color);
for (let j = 1; j < props.colorData[i].length - 1; j++) {
// props.colorData[i][j].point
//props.colorData[i][j].color
let border =
(right - x.getPixelForValue(props.colorData[i][j].point)) /
(right - left);
console.log(border);
if (border > 1) border = 1;
gradientSegment.addColorStop(
border,
props.colorData[i][j - 1].color
);
gradientSegment.addColorStop(
border,
props.colorData[i][j].color
);
}
gradientSegment.addColorStop(
1,
props.colorData[i][props.colorData[i].length - 1].color
);
gradients.push(gradientSegment);
}
return gradients;
},
borderColor: props.borderColor || "rgb(100,150,150)",
borderWidth: 1,
},
],
});
}, [props]);
return (
<div className={`${props.className} bar--hight`}>
{!!Chartdata && (
<Bar
options={{
indexAxis: "y", // Rotate the chart horizontally
maintainAspectRatio: false,
responsive: true,
scales: {
x: {
beginAtZero: true,
},
y: {
beginAtZero: true,
},
},
}}
data={Chartdata}
/>
)}
</div>
);
};
export default React.memo(BarChart);
`
在主要组件中:
<BarChart
data={Array(7).fill(10)}
labels={DUUMYY_LABLES}
colorData={colorData}
className="AnalyticCharts--charts--div"
/>
` 颜色数据如下所示:
[
[
{
"point": 0,
"color": "red"
},
{
"point": 10,
"color": "red"
}
],
[
{
"point": 0,
"color": "red"
},
{
"point": 5,
"color": "yellow"
},
{
"point": 7,
"color": "red"
},
{
"point": 10,
"color": "red"
}
],
[
{
"point": 0,
"color": "red"
},
{
"point": 10,
"color": "red"
}
],
[
{
"point": 0,
"color": "red"
},
{
"point": 10,
"color": "red"
}
],
[
{
"point": 0,
"color": "red"
},
{
"point": 10,
"color": "red"
}
],
[
{
"point": 0,
"color": "red"
},
{
"point": 10,
"color": "red"
}
],
[
{
"point": 0,
"color": "red"
},
{
"point": 10,
"color": "red"
}
]]
我想看到我的第二个条从 0 到 5 为红色,然后从 5 到 7 为黄色,从 7 到 10 再次为红色
为了使图表正确运行,我应该更改这些行,这样就可以了:
const gradientSegment =
ctx.createLinearGradient(right,0,left,0);
let border =
(left - x.getPixelForValue(props.colorData[i][j].point)) /
(left - right);