[英]Chart.js with plotting durations against dates
I am trying to create a chart with dates ( MMMM DD, YYYY
) on the x axis, and duration ( h:mm:ss
) on the y axis.我正在尝试创建一个图表,在 x 轴上带有日期( MMMM DD, YYYY
),在 y 轴上带有持续时间( h:mm:ss
)。 The below code supports dates (x) but not durations (y).下面的代码支持日期 (x) 但不支持持续时间 (y)。
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [moment("2009-04-11").format('MMMM DD, YYYY')],
datasets: [{
data: [{
x: "2009-04-11",
y: "01:20"
}],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
],
borderColor: [
'rgba(255, 99, 132, 1)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
type: 'time',
time: {
unit: 'minute'
}
}]
}
}
});
The following example illustrates how it can be done.下面的例子说明了它是如何完成的。 I assume the y
value '01:20'
from your code to be of format 'HH:mm'
.我假设您的代码中的y
值'01:20'
的格式为'HH:mm'
。
const data = [ { x: '2009-04-11', y: '01:20' }, { x: '2009-05-02', y: '01:40' }, { x: '2009-05-18', y: '01:10' } ]; new Chart(document.getElementById('myChart'), { type: 'line', data: { datasets: [{ label: 'My Dataset', data: data.map(o => ({ x: ox, y: moment.duration(oy) })), backgroundColor: 'rgba(255, 99, 132, 0.2)', borderColor: 'rgba(255, 99, 132, 1)', borderWidth: 1 }] }, options: { tooltips: { callbacks: { label: (tooltipItem, data) => moment.utc(data.labels[tooltipItem.index]).format('HH:mm') } }, scales: { yAxes: [{ ticks: { beginAtZero: true, stepSize: 1_200_000, callback: v => moment.utc(v).format('HH:mm') } }], xAxes: [{ type: 'time', time: { unit: 'days', displayFormats: { days: 'MMMM DD, YYYY' } } }] } } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.3.0/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script> <canvas id="myChart" height="90"></canvas>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.