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

React react-chartjs-2折线图添加X/Y轴标签的实现问题

解决方案

在Chart.js 2.x版本中,轴名称(刻度标签)需要通过scales配置项里的xAxes/yAxes数组中的scaleLabel字段来设置,以下是适配你所用版本的完整实现代码:

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

const CarCountChart = () => {
  // 示例数据
  const data = {
    labels: ['9:00', '10:00', '11:00', '12:00', '13:00'],
    datasets: [
      {
        label: 'Car Count',
        data: [15, 22, 30, 25, 18],
        borderColor: 'rgb(75, 192, 192)',
        tension: 0.1
      }
    ]
  };

  const options = {
    scales: {
      xAxes: [
        {
          scaleLabel: {
            display: true,
            labelString: 'time' // X轴名称
          }
        }
      ],
      yAxes: [
        {
          scaleLabel: {
            display: true,
            labelString: 'number of cars' // Y轴名称
          }
        }
      ]
    }
  };

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

export default CarCountChart;

关键配置说明

  • 由于你使用的是Chart.js 2.x版本,轴配置嵌套在scales.xAxes和scales.yAxes数组中(支持多轴场景)
  • scaleLabel.display设为true才会显示轴名称
  • scaleLabel.labelString用于定义轴的具体名称

内容的提问来源于stack exchange,提问作者Cindy Burker

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 14:40:15