2👍
You need to add a different label for each chart :
datasets: [
{
label: "chart1",
data: [1, 2, 3],
labels: ["category1", "category2", "category3"],
backgroundColor: [
"#79CAF2",
"#80DEEA",
"#A5D6A7",
],
hoverBackgroundColor: [
"#31B2F2",
"#00BCD4",
"#4CAF50",
]
},
{
label: "chart2",
data: [1, 2, 3, 4, 5],
labels: ["sub1", "sub2", "sub3", "sub4", "sub5"],
backgroundColor: [
"#79CAF2",
"#80DEEA",
"#A5D6A7",
"#C5E1A5",
"#FFF59D",
],
hoverBackgroundColor: [
"#31B2F2",
"#00BCD4",
"#4CAF50",
"#8BC34A",
"#FFEB3B",
]
},
]
0👍
The issue is with the first dataset being copied over the other dataset because the library cannot identify the difference between the two. And that is because there is no specification of unique keys (either key or label) for them.
While working with multiple datasets in the react-chartjs-2 library, the library needs to track the changes in the dataset series at any event that triggers re-rendering of the chart (such as tooltips, updating charts on onClick events, etc.).
In such cases, you can do one of the following:
- Add the
label
property on each dataset (by default, the library treats this as the key to identify the datasets.). These labels should be unique for each dataset.
render() {
const data = {
datasets: [
{
label:"chart1",
data: [1, 2, 3],
...
},
{
label:"chart2",
data: [1, 2, 3, 4, 5],
...
},
]
};
...
return (
<div className="h100per_200pix w100per margin_top_50">
<DoughnutChart data={data} options={options} ref="chart" />
</div>
)
}
- (Recommended) Add the
key
property on each dataset that specifies a
unique string. AdddatasetKeyProvider
prop to the chart component.
Then pass a function to thedatasetKeyProvider
prop that returns the unique key of each dataset.
render() {
const data = {
datasets: [
{
key:"D1",
label:"chart1",
data: [1, 2, 3],
...
},
{
key:"D2",
label:"chart2",
data: [1, 2, 3, 4, 5],
...
},
]
};
...
getDatasetKey = (d) => {return d.key};
return (
<div className="h100per_200pix w100per margin_top_50">
<DoughnutChart
datasetKeyProvider={this.getDatasetKey}
data={data} options={options} ref="chart" />
</div>
)
}
Source:stackexchange.com