所以我使用 Cordova 制作这个移动应用程序,它允许我使用 HTML、CSS 和 JavaScript。我目前使用 SQLite 作为数据库(工作方式几乎与 mySQL 相同),但这并不重要。我所做的就是从该数据库中获取数据。我得到了日期(数据添加到数据库的时间)和一个人的体重。
我使用的是线图,它在 Y 轴上显示权重,在 X 轴上显示数据。
我想要做的只是将月份显示为 x 轴上的标签,但仍使其单独显示每天的数据。例如,如果我添加 1 月 1 日、1 月 2 日和 1 月 3 日的数据。我希望能够在图表上将所有 3 天视为点,但在 X 轴上应该只显示“一月”。
我一直在研究 Chart.JS 的“时间”选项,但无法真正理解我应该如何做。
HTML:
<canvas id="myChart" style="margin-top: 20px;"></canvas>
JavaScript:
//these are the arrays that I will fill dynamically. Labels will be my months and data will be the weight
var labels = [];
var data = [];
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: labels,
datasets: [{
backgroundColor: 'rgba(255, 119, 0, 0.5)',
borderColor: 'rgba(255, 119, 0, 1)',
data: data
}]
},
// Configuration options go here
options: {
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
最佳答案
在 x 轴上使用时间类型。使用 time: { unit: 'month' }
(始终为月)或 minUnit
(必要时为月和年),您可以获得月份标签。
作为数据标签,您需要传递日期
或时刻
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'month'
}
}],
}
Here是一个完整的例子。 检查moment docs对于日期,尤其是日期的创建和解析。 Chart.js 使用时刻日期,因此它非常重要(而且非常简单)。
关于javascript - ChartJS x 轴仅显示一年中的月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57730601/