我在 StackOverflow 和 GitHub 上发现了许多其他问题,但没有一个对我有用......
我有一个使用 ChartJS 构建的图表。当我单击任何条(橙色、绿色或红色)时,我想获得相应的值。有什么办法可以做到这一点?
我使用的 npm 包是 react-chartjs-2。
它有 2 个我发现可能有帮助的 Prop ,但在这种情况下不知道如何使用它。它们是 getElementsAtEvent 和 onElementsClick 。这些 Prop 在使用时会提供大量数据,除了我刚刚单击的栏的值。
这就是我导入组件的方式import { Bar } from "react-chartjs-2";
这就是我使用组件的方式
<Bar
data={barData}
height={275}
options={{
maintainAspectRatio: false,
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
}}
/>;
而变量barData如下:const barData = {
labels: [
"04-07-2020",
"05-07-2020",
"06-07-2020",
"07-07-2020",
"08-07-2020",
"09-07-2020",
"10-07-2020",
],
datasets: [
{
label: "Cases",
borderWidth: 1,
backgroundColor: "#ffc299",
borderColor: "#cc5200",
hoverBackgroundColor: "#ed873e",
hoverBorderColor: "#e35f00",
data: [673165, 697413, 719664, 742417, 767296, 793802, 820916],
},
{
label: "Recovered",
borderWidth: 1,
backgroundColor: "#b3ffb3",
borderColor: "#00ff00",
hoverBackgroundColor: "#55cf72",
hoverBorderColor: "#2c9c46",
data: [409083, 424433, 439934, 456831, 476378, 495513, 515386],
},
{
label: "Deaths",
borderWidth: 1,
backgroundColor: "#de8078",
borderColor: "#fa6457",
hoverBackgroundColor: "#d73627",
hoverBorderColor: "#ff4636",
data: [19268, 19693, 20159, 20642, 21129, 21604, 22123],
},
],
};
这是图表任何帮助表示赞赏
最佳答案
由于您的数据以某种方式构造,因此当单击条形时,将返回一个大小为 3 的数组作为 elem
.您可以根据需要从那里提取数据。
使用 onElementsClick
:
<Bar
data={barData}
height={275}
onElementsClick={elem => {
var data = barData.datasets[elem[0]._datasetIndex].data;
console.log("Cases", data[elem[0]._index]);
data = barData.datasets[elem[1]._datasetIndex].data;
console.log("Recovered", data[elem[1]._index]);
data = barData.datasets[elem[2]._datasetIndex].data;
console.log("Deaths", data[elem[2]._index]);
}}
options={{
maintainAspectRatio: false,
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
}}
/>;
elem
填充有单击的元素。您可能需要稍微调整此代码以准确实现您正在寻找的内容,具体取决于您要对该数据执行的操作。评论中的沙盒。
关于javascript - react ChartJS 2 : Get data on clicking the chart,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62852068/