Chart.js 3.0/3.8版本如何正确显示X轴标题 配置不显示解决
问题根源
你的配置层级写错了。Chart.js 3.0及以上版本中,坐标轴标题(轴标签)的相关配置不能直接写在scales.x的根节点下,必须嵌套在title子配置对象中才会被识别,你现在把text、color这类标题配置直接放在x轴根属性里,框架不会把这些参数识别为轴标题配置,自然不会显示。
修复步骤
把scales部分的配置调整为如下结构即可:
options: { scales: { x: { display: true, title: { display: true, // 轴标题默认隐藏,必须手动开启显示 text: 'Price', color: 'rgb(12, 70, 14)' } } } }
你之前的配置还有两个容易踩的小问题:
- 之前写的颜色值
rgb (12, 70, 14)在rgb和括号之间多了空格,会导致颜色解析失败,要去掉空格 - 轴标题自身有独立的
display控制属性,默认值为false,就算配置了text,不把这个属性设为true也不会渲染标题
修复后完整可运行代码
<html> <head> </head> <body> <canvas id="myChart" width="400" height="400"></canvas> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script> const labels = [ '1740.00', '1750.00', '1760.00', ]; const data = { labels: labels, datasets: [{ label: 'My First dataset', backgroundColor: 'rgb(12, 70, 14)', borderColor: 'rgb(12, 70, 14)', data: [444000, 790000, 1550000], }] }; const config = { type: 'line', data: data, options: { scales: { x: { display: true, title: { display: true, text: 'Price', color: 'rgb(12, 70, 14)' } } } } }; const myChart = new Chart( document.getElementById('myChart'), config ); </script> </body> </html>
内容的提问来源于stack exchange,提问作者user626920
相关产品推荐
相关产品推荐

