Updating chartJS with dynamic data

好久不见. 提交于 2021-02-19 01:32:12

问题


my plan is to display a temperature graph using chartJS that looks somewhat like the google one when you look up local weather. I am using data from openweathermap and would like to update the graph every 3 hours.

Unfortunatly I wasn't able to find a solution that worked for me to pass the data i get from openweathermaps to the chart array and update it.

In the documentation an update function is mentioned (http://www.chartjs.org/docs/latest/developers/updates.html) but I think I am too much of a bloody beginner to really understand how to apply it in this case.

This right here is the code I use to draw a chart with static numbers:

let myChart = document.getElementById('myChart').getContext('2d');

var WeatherChart = new Chart(myChart, {
 type:'line', 
 data:{
    labels:['3h', '6h', '9h', '12h',],
    datasets:[{data:[12, 16, 16, 8],}]
 },

options:{}
});

How would I go about using data from a variable or an array to update the chart?


回答1:


This answer will depend on how you are trying to update the information. Assuming you are using exactly as you gave, you will put a timer for every 3 hours and run this function:

function updateWeatherChart(){
    WeatherChart.data.datasets[0].data = [1, 2, 3, 4];
    WeatherChart.update();  
}

You can have something that, like in the documentation says, runs through the data and deletes it first. Or, you can just reassign it with the new information you want to update the existing chart with.

Keep in mind that instead of [1, 2, 3, 4] you will have to run code before to get the new information and replace the array with your own array. [1, 2, 3, 4] was just a test case.



来源:https://stackoverflow.com/questions/50915996/updating-chartjs-with-dynamic-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!