javascript 实时更新chart.js条形图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30610439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Updating chart.js bar graph in real time
提问by user1010101
I am using Chart.js
to create a simple bar chart with only two rows and 2 sets of data. I am new to using the library and after reading the examples, I feel comfortable with most of the things there. Here is what I have so far
我正在使用Chart.js
创建一个只有两行和两组数据的简单条形图。我是使用库的新手,在阅读示例后,我对其中的大部分内容感到满意。这是我到目前为止所拥有的
JS code for graph:
图的JS代码:
var helpers = Chart.helpers;
var canvas = document.getElementById('bar');
var barChartData = {
labels: ["IBM", "Microsoft"],
datasets: [{
label: "Product A",
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
data: [25, 75]
}, {
label: "Product B",
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
data: [75, 25]
}]
}
//
var bar = new Chart(canvas.getContext('2d')).Bar(barChartData, {
tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>kb",
animation: false,
})
;
Now, I was wondering if it is possible to update this graph if the data was changed in real time without refreshing the page. For instance if every second the data values keep swapping or something random happens the graph should reflect the changes. I have searched a lot but not found proper document or tutorial explaining this and I would highly appreciate it if someone can show me how to do this.
现在,我想知道是否可以在不刷新页面的情况下实时更改数据来更新此图表。例如,如果数据值每秒都在交换或发生随机事件,则图表应反映变化。我已经搜索了很多,但没有找到解释这一点的正确文档或教程,如果有人能告诉我如何做到这一点,我将不胜感激。
This is the FIDDLEI have created for work so far.
回答by Anand Sudhanaboina
You can just use the method addData()
, Example:
您可以只使用该方法addData()
,例如:
bar.addData([40, 60], "Google");
Working example - http://jsbin.com/kalilayohu/1/
回答by Taioli Francesco
this is the code
这是代码
var canvas = document.getElementById('myChart');
var myBarChart = Chart.Bar(canvas,{
data:{
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
data: [65, 59, 80, 81, 56, 55, 40],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}
]
},
options:{
scales: {
yAxes:[{
stacked:true,
gridLines: {
display:true,
color:"rgba(255,99,132,0.2)"
}
}],
xAxes:[{
gridLines: {
display:false
}
}]
}
}
});
//to update do this
//要更新这样做
myBarChart.data.datasets[0].data[4] = 50;//this update the value of may
myBarChart.update();