[英]Switch chart.js data with button click
I am trying to build a dynamic chart using chart.js but I cannot figure out how to swap datasets when clicking buttons. 我正在尝试使用chart.js构建动态图表,但是我无法弄清楚如何在单击按钮时交换数据集。 Some answers here suggest using update() and destroy() with version 2 but they have not worked for me. 这里的一些答案建议在版本2中使用update()和destroy(),但它们对我没有用。 I can destroy the data but not then draw the new chart with the correct data set. 我可以销毁数据,但不能用正确的数据集绘制新图表。 Here is the jsfiddle and code below: 这是下面的jsfiddle和代码:
HTML: HTML:
<canvas id="forecast" width="300" height="150"></canvas>
<button id="0" type="button" >Dataset 1</button>
<button id="1" type="button" >Dataset 2</button>
JavaScript: JavaScript的:
var chart_labels = ['06:00', '09:00', '12:00', '15:00', '18:00', '21:00'];
var temp_dataset = ['1', '8', '10', '10', '9', '7'];
var rain_dataset = ['0', '0', '6', '32', '7', '2'];
var ctx = document.getElementById("forecast").getContext('2d');
var config = {
type: 'bar',
data: {
labels: chart_labels,
datasets: [
{
type: 'line',
label: "Temperature (Celsius)",
yAxisID: "y-axis-0",
fill: false,
data: temp_dataset,
},
{
type: 'bar',
label: "Precipitation (%)",
yAxisID: "y-axis-1",
data: rain_dataset,
}]
},
options: {
scales: {
yAxes: [{
position: "left",
"id": "y-axis-0",
}, {
position: "right",
"id": "y-axis-1",
}]
}
}
};
var forecast_chart = new Chart(ctx, config);
$("#1").click(function (){
var chart_labels = ['00:00', '03:00', '06:00', '09:00', '12:00', '15:00', '18:00', '21:00'];
var temp_dataset = ['5', '3', '4', '8', '10', '11', '10', '9'];
var rain_dataset = ['0', '0', '1', '4', '19', '19', '7', '2'];
forecast_chart.destroy();
forecast_chart = new Chart(ctx, config);
});
edit* I should add that the initial values should load with the page, the second values on button2 click and the original values on button1 click 编辑*我应该补充一点,初始值应随页面加载,button2上的第二个值单击,而button1上的原始值单击
That could be accomplished by replacing the data
and labels
array on button click ... 这可以通过替换按钮单击上的data
和labels
数组来实现。
$("#0").click(function() {
var data = forecast_chart.config.data;
data.datasets[0].data = temp_dataset;
data.datasets[1].data = rain_dataset;
data.labels = chart_labels;
forecast_chart.update();
});
$("#1").click(function() {
var chart_labels = ['00:00', '03:00', '06:00', '09:00', '12:00', '15:00', '18:00', '21:00'];
var temp_dataset = ['5', '3', '4', '8', '10', '11', '10', '9'];
var rain_dataset = ['0', '0', '1', '4', '19', '19', '7', '2'];
var data = forecast_chart.config.data;
data.datasets[0].data = temp_dataset;
data.datasets[1].data = rain_dataset;
data.labels = chart_labels;
forecast_chart.update();
});
Here's the working fiddle 这是工作的小提琴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.