繁体   English   中英

在带有 React 的 Chartjs 2.9.x 中使用 chartjs-plugin-annotation 0.5.7

[英]Use chartjs-plugin-annotation 0.5.7 in Chartjs 2.9.x with React

我无法在 Chartjs 中配置插件 chartjs-plugin-annotation。

从文档中,我安装了 V 0.5.7,因为我使用的是 Chart.js V 2.9.4。

这是我的配置:

注册插件:

import Chart from "chart.js";
import annotationPlugin from "chartjs-plugin-annotation";

Chart.plugins.register(annotationPlugin);
//Chart.pluginService.register(annotationPlugin); //also tried this but doesn't work

这里是选项配置(简化),我也尝试在“插件”中包装“注释”,但它不起作用:

  scales: {
    yAxes: [
      {
        scaleLabel: {
          ...
        },
        ticks: {
          ...
        },
        gridLines: {
          ...
        },
      },
    ],
    xAxes: [
      {
        gridLines: {
          ...
        },
        ticks: {
          ...
        },
      },
    ],
  },
  maintainAspectRatio: false,
  legend: {
    ...
    labels: {
      ...
    },
  },
  tooltips: {
    ...
  },
  annotation: {
    annotations: [
      {
        type: "line",
        mode: "horizontal",
        scaleID: "yAxes",
        value: 2.62,
        borderColor: "white",
        borderWidth: 4,
      },
    ],
  },
  hover: {
    ...
  },

我究竟做错了什么?

看起来您正在尝试实现注释插件,就好像您将它集成到当前的 chart.js 版本一样。 例如,您在plugins中定义您的注释。

这是一个适用于给定版本的示例。 请注意,我立即在options中添加了annotation object,它给出了所需的注释。 (在我的例子中,以红线的形式出现。)

import React, { useEffect, useRef } from "react";
import Chart from "chart.js";
import annotationPlugin from "chartjs-plugin-annotation";

Chart.pluginService.register(annotationPlugin);

const LineGraph = () => {
  const chartRef = useRef(null);

  useEffect(() => {
    if (chartRef?.current) {
      const chartToDraw = chartRef.current.getContext("2d");

      new Chart(chartToDraw, {
        type: "line",
        data: {
          labels: ["Jan", "Feb", "March"],
          datasets: [
            {
              label: "Sales",
              data: [86, 67, 91]
            }
          ]
        },
        options: {
          annotation: {
            drawTime: "afterDatasetsDraw", // (default)
            events: ["click"],
            dblClickSpeed: 350, // ms (default)
            annotations: [
              {
                drawTime: "afterDraw",
                id: "a-line-1",
                type: "line",
                mode: "horizontal",
                scaleID: "y-axis-0",
                value: "25",
                borderColor: "red",
                borderWidth: 2
              }
            ]
          }
        }
      });
    }
  }, []);

  return (
    <div className={{ width: "100%", height: 500 }}>
      <canvas id="myChart" ref={chartRef} />
    </div>
  );
};

export default LineGraph;

你可以看到它在这里工作: https://codesandbox.io/s/chart-js-2-9-4-annotation-example-f3h7d?file=/src/LineGraph.js

Chart.js 0.5.7 插件注释文档: https://www.chartjs.org/chartjs-plugin-annotation/0.5.7/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM