ChartJS React+图表JS V3:注解不起作用

6yoyoihd  于 2022-11-07  发布在  Chart.js
关注(0)|答案(2)|浏览(142)

我使用的是react-chartjs-2 v4.1和ChartJS v3.8的打印脚本。
我想在条形图上画一条水平线,如下所示:

我发现许多写了一半的例子,我无法创建一个功能性的例子。我找不到任何完整的,工作的例子如何使用注解。

我的代码

我已经将chartjs-plugin-annotation包添加到我的项目中。
下面是一个react组件的代码,显示了截图的图形。然而,注解不起作用。有人能告诉我代码有什么问题吗?

import React from 'react';
import { Bar } from 'react-chartjs-2';

export const MyChart: React.FC = () => {
  const options2 = {
    plugins: {
      legend: {
        display: false,
      },
      annotation: {
        annotations: [
          {
            id: 'a-line-1',
            type: 'line',
            mode: 'horizontal',
            scaleID: 'y',
            value: 1.0,
            borderColor: 'red',
            borderWidth: 4,
            label: {
              enabled: false,
              content: 'Test label',
            },
          },
        ],
      },
    },
  };

   const data2 = {
    labels:   [ 'a', 'b'],
    datasets: [ { data: [1, 2] } ],
   };

   return (<Bar options={options2} data={data2} height={150} />
   );
};
lndjwyie

lndjwyie1#

不导入和注册注解插件:

import { Chart } from 'chart.js';
import annotationPlugin from 'chartjs-plugin-annotation';

Chart.register(annotationPlugin);
wydwbb8l

wydwbb8l2#

下面是一个基于LeeLenalee's answer的完整工作示例。
对相关代码的更改:

  • 导入和注册注解插件
  • 将注解类型设置为type: 'line' as const(而不仅仅是type: 'line')。否则typescript会抱怨。
import React from 'react';
import { Bar } from 'react-chartjs-2';
import { Chart } from 'chart.js';
import annotationPlugin from 'chartjs-plugin-annotation';

Chart.register(annotationPlugin);

export const MyChart: React.FC = () => {
  const options2 = {
    plugins: {
      legend: {
        display: false,
      },
      annotation: {
        annotations: [
          {
            id: 'a-line-1',
            type: 'line' as const, // important, otherwise typescript complains
            mode: 'horizontal',
            scaleID: 'y',
            value: 1.0,
            borderColor: 'red',
            borderWidth: 4,
            label: {
              enabled: false,
              content: 'Test label',
            },
          },
        ],
      },
    },
  };

   const data2 = {
    labels:   [ 'a', 'b'],
    datasets: [ { data: [1, 2] } ],
   };

   return (<Bar options={options2} data={data2} height={150} />
   );
};

相关问题