在过去的一个小时里,我一直在尝试让 Chart.js 在同一页面上呈现两个折线图。我已确保我的画布元素 ID 是唯一的,我的变量也是如此。
我能够成功加载第一个图表,ctx或canvas,但不是第二个图表,ctx2或canvas2。
这是使用 chart.js v2.8.0
输入数据定义在index.html
var lineChartData = {
labels: ['-18:00', '-15:00', '-12:00', '-9:00', '-6:00', '-3:00', '0:00'],
datasets: [{
label: 'Temperature (F)',
borderColor: window.chartColors.red,
backgroundColor: window.chartColors.red,
fill: false,
data: [
60 - randomScalingFactor(),
55 - randomScalingFactor(),
57 - randomScalingFactor(),
58 - randomScalingFactor(),
59 - randomScalingFactor(),
65 - randomScalingFactor(),
73 - randomScalingFactor()
],
yAxisID: 'y-axis-1',
}]
};
var avgLineChartData = {
labels: ['1', '1', '1', '1', '1', '1', '1'],
datasets: [{
label: 'Avg Temperature (F)',
borderColor: window.chartColors.green,
backgroundColor: window.chartColors.green,
fill: false,
data: [
65 - randomScalingFactor(),
53 - randomScalingFactor(),
58 - randomScalingFactor(),
54 - randomScalingFactor(),
62 - randomScalingFactor(),
65 - randomScalingFactor(),
74 - randomScalingFactor()
],
yAxisID: 'y-axis-1',
}]
};
图表绘图index.html
window.onload = function () {
var ctx = document.getElementById('canvas').getContext('2d');
new Chart(ctx, {
type: 'line',
data: lineChartData,
options: {
responsive: true,
hoverMode: 'index',
stacked: false,
title: {
display: true,
text: 'Temp(F)/Humidity(%) per 15 Hours'
},
scales: {
yAxes: [{
type: 'linear', // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: 'left',
id: 'y-axis-1',
ticks: {
beginAtZero: true,
max: 100,
},
}, {
type: 'linear', // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: 'right',
id: 'y-axis-2',
ticks: {
beginAtZero: true,
max: 100,
},
// grid line settings
gridLines: {
drawOnChartArea: false, // only want the grid lines for one axis to show up
},
}],
},
elements: {
line: {
tension: 0.3
}
}
}
});
var ctx2 = document.getElementById('canvas2').getContext('2d');
new Chart(ctx2, {
type: 'line',
data: avgLineChartData,
options: {
responsive: true,
hoverMode: 'index',
stacked: false,
title: {
display: true,
text: 'Avg Temp(F)/Humidity(%) per 7 Days'
},
scales: {
yAxes: [{
type: 'linear', // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: 'left',
id: 'avg-y-axis-1',
ticks: {
beginAtZero: true,
max: 100,
},
}, {
type: 'linear', // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: 'right',
id: 'avg-y-axis-2',
ticks: {
beginAtZero: true,
max: 100,
},
// grid line settings
gridLines: {
drawOnChartArea: false, // only want the grid lines for one axis to show up
},
}],
},
elements: {
line: {
tension: 0.3
}
}
}
});
};
定义的画布元素index.html
<div class="container">
<canvas id="canvas"></canvas>
<canvas id="canvas2"></canvas>
</div>