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
相关产品推荐
相关产品推荐

