如何使用charts.js设置折线图的x、y轴和标题



这是使用charts.js。此代码只生成折线图,但不显示标题、x轴和y轴。我想在图上添加标题和这两个轴的名称。哪里出了问题,你该怎么解决?我还想让y轴从0开始向上。

async function chartDisplay() {
await getData1();
await getData2();
const ctx = document.getElementById('chart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'line',
data: {
labels: xLabels,
datasets: [{
data: ratingDataI,
label: "data1",
borderColor: "#3E95CD",
fill: false
},
{
data: ratingDataA,
label: "data2",
borderColor: "#3E95CD",
fill: false
}
]
},
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js Line Chart'
},
tooltips: {
mode: 'label',
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
x: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Dates'
}
}],
y: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Value'
}
}]
}
}
});
}

x和y不应该是数组,而应该是对象,而且scaleLabel道具现在被称为title。有关所有更改,请阅读迁移指南(https://www.chartjs.org/docs/master/getting-started/v3-migration.html)

示例:

var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
}]
},
options: {
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: 'yAxis'
}
},
x: {
title: {
display: true,
text: 'xAxis'
}
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.js"></script>
</body>

最新更新