react-chartjs-2的Line组件仅渲染竖线而非预期斜线问题求助
问题原因
- 数据点未按X轴数值排序:你传入的数据集
[{x:10,y:20},{x:15,y:10},{x:12,y:4}]中,第三个点的x值12小于第二个点的x值15,Chart.js默认按传入顺序连线,不会自动排序,导致连线出现回折的异常效果 - 未明确配置X轴类型:使用{x,y}格式的数值坐标时,需要手动指定X轴为
linear线性类型,默认的分类坐标轴无法正确识别数值型x字段 - 新版本react-chartjs-2需要手动注册依赖组件,缺失注册逻辑也会导致渲染异常
修复方案
修改后的完整可运行代码如下:
import React from 'react' import { Line } from 'react-chartjs-2'; import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, } from 'chart.js'; // 注册Chart.js所需组件 ChartJS.register( CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend ); function Linegraph() { // 按x值从小到大排序数据 const sortedData = [{x:10,y:20},{x:15,y:10},{x:12,y:4}].sort((a,b) => a.x - b.x); return ( <div className="linegraph"> <Line data={{ datasets:[{ type:"line", data: sortedData, backgroundColor:"black", borderColor:'#5AC53B', borderWidth:2, pointBorderColor:'rgba(0,0,0,0)', pointBackgroundColor:'rgba(0,0,0,0)', pointHoverBackgroundColor:'#5AC53B', pointHoverBorderColor:"#000000", pointHoverBorderWidth:4, pointHoverRadius:6, }] }} // 添加坐标轴配置 options={{ scales: { x: { type: 'linear' }, y: { beginAtZero: true } } }} /> </div> ) } export default Linegraph
内容的提问来源于stack exchange,提问作者dreamstate
相关产品推荐
相关产品推荐

