I'm trying to plot the wind speed in a canvas graph using Charts.js. The data (wind speed and wind direction) comes from a JSON URL. Everything works fine with the code and the plot looks like this:
I was able to add the arrows by using the Plugins from Charts.js, a formatter
and a rotation
function, but what I would like to do is to have the arrows rotated according to the wind direction angle that comes from the JSON.
The JSON file has a format that looks like this:
So far, a part of the code looks like this:
Current = Date.now(); $.getJSON("https://api.openweathermap.org/data/2.5/onecall?lat={LAT}&lon={LONG}&dt=" + Current + "&appid={MY API CODE}", function(data) { $.each(data.hourly, function(key, value) { var d = new Date(value.dt * 1000); minutes = "0" + d.getMinutes() var date_corrected = d.getFullYear() + "-" + [d.getMonth() + 1] + '-' + d.getDate() + ' ' + [d.getHours()] + ':' + minutes.substr(-2); dataOpen1.push({ x: date_corrected, y: value.wind_speed }); dataOpen2.push({ x: date_corrected, y: value.wind_deg }); }); var WIND = new Chart(vant, { plugins: [ChartDataLabels], type: 'line', data: { labels: dataOpen1.map(x => xx), datasets: [{ data: dataOpen1.map(y => yy), label: 'Viteza vantului ', borderColor: "#3e95cd", fill: true }, ] }, options: { plugins: { datalabels: { backgroundColor: 'white', borderRadius: 20, borderWidth: 3, borderDashOffset: 20, color: 'black', font: { size: 18 }, formatter: function(value) { return '\➣' }, rotation: function(ctx) { return ctx.dataset.data[ctx.dataIndex] * 25; }, padding: 0 } }, }); });
So I would like to get the values from dataOpen2
(with the wind direction) and use it to set the rotation angle of the arrows per each data set. I know that the code has to be here:
rotation: function(ctx) { ....... return ctx.dataset.data[ctx.dataIndex] * 25; },
But I don't really have any idea how to do it.
As per Issue at github repository for CHARTJS https://github.com/chartjs/Chart.js/issues/5667
You may need to adjust your data in following way:
dataOpen1.push({
x: date_corrected,
y: value.wind_speed
d: value.wind_deg
});
And then you can modify using datalable plugin your function as
rotation: function(ctx) { return ctx.dataset.data[ctx.dataIndex].d; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.