【问题标题】:Adding data labels inside charts in ReactJS is not working?在 ReactJS 中的图表内添加数据标签不起作用?
【发布时间】:2021-09-03 21:08:48
【问题描述】:

例如How to display data on top of line chart

实施时面临的问题:

chartjs Plugin "chartjs-plugin-datalabels:1.0.0" import is throws below error

TypeError : 无法读取未定义的属性“扩展”。

通过将标签插件包更改为测试版本2.0.0-rc.1解决了上述错误

codeandbox 的链接将找到HERE

此处提出了类似的问题,但解决方案无法解决我的问题。

我们将不胜感激任何形式的帮助。

import React, { Fragment } from "react";
import { Line } from "react-chartjs-2";
import "chartjs-plugin-datalabels";

const styles = {
  dangerColor: {
    color: "red"
  },
  geen: {
    color: "green"
  }
};

const data = {
  labels: ["Jan", "Feb", "Mar", "Apr", "May"],
  datasets: [
    {
      label: "Avg interest by month",
      data: [0.7, 0.81, 0.71, 0.87, 0.9],
      fill: false,
      backgroundColor: "transparent",
      borderColor: "#06a1e1",
      tension: 0.1,
      borderWidth: 4
    }
  ]
};

const options = {
  maintainAspectRatio: false,
  scales: {
    x: {
      grid: {
        display: false
      }
    },
    y: {
      display: false,
      grid: {
        display: false
      }
    }
  },
  plugins: {
    legend: {
      display: false
    },
    title: {
      display: true,
      text: "Avg interest by month (days)",
      padding: {
        bottom: 30
      },
      weight: "bold",
      color: "#00325c",
      font: {
        size: 13
      },
      align: "start"
    },
    datalabels: {
      display: true,
      color: "white"
    }
  }
};

const LineChart = () => (
  <Fragment>
    <div style={{ height: "300px" }}>
      <Line data={data} options={options} />
    </div>
  </Fragment>
);


export default LineChart;

这就是我的 Package.json 依赖项的样子

{
    "chart.js": "^3.3.2",
    "chartjs-plugin-datalabels": "^2.0.0-rc.1",
    "react": "^17.0.2",
    "react-chartjs-2": "^3.0.3",
    "react-dom": "^17.0.2",
    "react-scripts": "^4.0.3",
    "web-vitals": "^1.1.2"
}

【问题讨论】:

    标签: reactjs charts react-chartjs-2


    【解决方案1】:

    react-chartjs-2 包包含一个插件属性,可以在组件上设置。

    更改导入来源:

    import "chartjs-plugin-datalabels";
    

    到:

    import ChartDataLabels from 'chartjs-plugin-datalabels';
    

    在您的组件上,添加保存导入值的插件变量。

    来自:

    <Line data={data} options={options} />
    

    到:

    <Line data={data} plugins={[ChartDataLabels]} options={options} />
    

    【讨论】:

    • 我搜索了一整天并尝试了一切,只有你的答案是有效的谢谢!
    • 我有一个多轴图表。你知道如何分别为每个轴设置数据标签的格式吗?
    • 我设法解决了:您需要为每个数据集添加数据标签。
    【解决方案2】:

    我找到了问题并更新了沙盒

    你可以在这里找到链接 https://codesandbox.io/s/quizzical-hooks-zcg91?file=/src/components/LineChart.jsx

    问题在于 chart.js

    import { Chart } from "chart.js";
    import ChartDataLabels from "chartjs-plugin-datalabels";
    Chart.register(ChartDataLabels);
    

    插件注册方法在chart.js 3.x版本更新

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-17
      相关资源
      最近更新 更多