javascript - 如何在 react-chartjs-2 中的饼图图例中显示值
问题描述
我正在为我的仪表板使用 react-Chartjs-2 饼图。根据要求,我必须在图例中显示带有数据的两个标签。我在我的应用程序中使用的以下组件
import React, { Component } from "react";
import { Doughnut } from "react-chartjs-2";
class DoughnutChart extends Component {
constructor(props) {
super(props);
}
render() {
const chartdata = {
labels: ["Newly Added", "Edited", "Deleted"],
datasets: [
{
label: "Markets Monitored",
backgroundColor: [
"#83ce83",
"#959595",
"#f96a5d",
"#00A6B4",
"#6800B4",
],
data: [9, 5, 3],
},
],
};
return (
<Doughnut
data={chartdata}
options={{
legend: { display: true, position: "right" },
datalabels: {
display: true,
color: "white",
},
tooltips: {
backgroundColor: "#5a6e7f",
},
}}
/>
);
}
}
export default DoughnutChart;
解决方案
一种方法是在创建图表之前定义数据和标签。然后您可以使用 .map 方法将数据添加到标签中。
import React, { Component } from "react";
import { Doughnut } from "react-chartjs-2";
class DoughnutChart extends Component {
constructor(props) {
super(props);
}
render() {
let data = [9, 5, 3]
let labels = ["Newly Added", "Edited", "Deleted"]
let customLabels = labels.map((label,index) =>`${label}: ${data[index]}`)
const chartdata = {
labels: customLabels,
datasets: [
{
label: "Markets Monitored",
backgroundColor: [
"#83ce83",
"#959595",
"#f96a5d",
"#00A6B4",
"#6800B4",
],
data: data,
},
],
};
return (
<Doughnut
data={chartdata}
options={{
legend: { display: true, position: "right" },
datalabels: {
display: true,
color: "white",
},
tooltips: {
backgroundColor: "#5a6e7f",
},
}}
/>
);
}
}
export default DoughnutChart;
推荐阅读
- html - 如果满足条件,HTML 显示文件列表
- c# - 使用 NETCore 2.1 在 Cognito 用户池中拒绝注册请求
- excel - 如何使用 ActiveCell & Formulas & Autofit Columns 简化代码?
- javascript - 基于值数组的嵌套 Firebase 查询 ASYNC 问题
- asp.net-mvc - 利用控制器和视图中的继承
- c# - 无法使用 Windows UWP 访问蓝牙特征值?
- mapping - 在本体之间映射类和属性
- javascript - 加载时背景图像不会“模糊”
- mysql - 按发票金额和物品总和订购客户
- mysql - ERROR 1064 (42000) 即使在教科书代码中