Chart.js图表主标题、坐标轴标题不显示及图例设置失效问题咨询
Chart.js配置失效问题排查及解决方案
核心原因
你使用的是Chart.js v3及以上版本,但参考的是v2版本的配置规则,两者配置结构存在不兼容的破坏性调整,是所有配置失效的核心原因。
具体问题及修正方案
- 主标题不显示:v3版本开始标题属于插件配置,需从
options.title移动到options.plugins.title层级 - 坐标轴标题不显示:v3移除了
scaleLabel属性,需替换为title属性,且x轴配置需改为对象格式(原数组写法仅v2支持) - 图例位置不生效:v3版本图例同样属于插件配置,需从
options.legend移动到options.plugins.legend层级 - 额外注意:你当前
datasets[0].label处于注释状态,即便图例配置生效也没有内容可展示,需取消注释 - 附加优化:v3版本中网格线配置属性已从
gridLines改为grid,修正后原有网格线规则才能生效
修正后的完整配置代码
let dataSize = 30; let readings = new Array(dataSize); const data = { // X axis labels labels: new Array(dataSize), datasets: [{ label: 'My Input', // 取消注释,图例需要该字段展示内容 data: readings, // the data to chart backgroundColor: 'rgba(123, 83, 252, 80)', borderColor: "rgba(255, 0, 0,1)", borderWidth: 1.2, pointBorderColor: "rgba(255, 0, 0, 1)", pointRadius: 0.2 // point size }] }; const config = { type: 'line', // type of chart data: data, // the data options: { animation: false, // remove animation to speed drawing up responsive: true, maintainAspectRatio: false, // 新增plugins层级放置标题、图例等插件类配置 plugins: { title: { display: true, text: 'Tarrif' }, legend:{ position: 'bottom' } }, scales: { // axis ranges: y: { // 替换scaleLabel为title配置坐标轴标题 title: { display: true, text: 'Y axis Title' }, min: 0, max: 260, // 替换gridLines为grid grid: { display: true, drawBorder: false //hide the chart edge line } }, // x轴从数组格式改为对象格式 x: { grid: { display: false }, title: { display: true, text: 'X axis Title' }, min:0 } } } };
问题原图

内容的提问来源于stack exchange,提问作者ee-diary
相关产品推荐
相关产品推荐

