You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Next.js项目的Chart.js图表中添加平均线

在Next.js中给Chart.js添加平均线(annotation插件)的可行方案

1. 安装annotation插件

首先需要安装独立的chartjs-plugin-annotation包,执行以下命令:

npm install chartjs-plugin-annotation
# 或
yarn add chartjs-plugin-annotation

2. 导入并注册插件

修改你的Chart.js导入和注册代码,添加Annotation相关内容:

import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js';
import { Bar } from 'react-chartjs-2';
// 导入annotation插件
import annotationPlugin from 'chartjs-plugin-annotation';

// 注册插件到ChartJS
ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend,
  annotationPlugin // 新增这一行
);

3. 修改配置项,添加平均线设置

在你的options对象中,添加annotation插件的配置,定义平均线的样式、位置等:

export const options = {
  plugins: {
    tooltip: {
      callbacks: {
        title: (context: any) => {
          return context[0].label;
        }
      }
    },
    title: {
      display: true,
      text: 'Egg Burn',
    },
    // 新增annotation配置
    annotation: {
      annotations: {
        // 定义一条水平平均线,id可自定义
        averageLine: {
          type: 'line',
          yMin: 50, // 平均线对应的y轴数值,根据你的数据调整
          yMax: 50,
          borderColor: '#ff0000', // 线条颜色
          borderWidth: 2, // 线条宽度
          borderDash: [5, 5], // 虚线样式,不需要可去掉
          // 可选:添加标签
          label: {
            content: '平均线',
            enabled: true,
            position: 'end',
          }
        }
      }
    }
  },
  responsive: true,
  scales: {
    x: {
      stacked: false,
      grid: {
        display: false
      },
      ticks: { // 修正:原callback需放在ticks对象下才生效
        callback: function (value: any, index: any, ticks: any) {
          return '$' + value;
        },
      },
    },
    y: {
      stacked: false,
      grid: {
        display: false
      }
    },
  },
};

4. 组件使用

如果是Next.js App Router环境,需要在组件顶部加上'use client'指令,其余保持原有代码即可:

'use client';

// ... 上述导入和配置代码 ...

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

常见问题排查

  • 确保插件版本与Chart.js版本兼容:chartjs-plugin-annotation v2.x对应Chart.js v4.x,v1.x对应Chart.js v3.x。
  • 检查yMin和yMax数值是否在你的数据范围内,否则平均线可能不会显示。
  • App Router下必须添加'use client',因为react-chartjs-2属于客户端组件。

内容的提问来源于stack exchange,提问作者wmn nisal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 18:48:24