Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating chartJS with dynamic data

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?

like image 536
Ray_Lion Avatar asked Jun 18 '18 19:06

Ray_Lion


1 Answers

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.

like image 90
Matt Avatar answered Nov 19 '22 10:11

Matt