I’m trying to plot a grouped bar chart adding traces dynamically from JSON data.
From the console.log it appears that the data passed to the chart is correctly formed.
Something like this for every trace:
{x: ["00:00 - 04:00", "04:00 - 08:00", "08:00 - 12:00","12:00 - 16:00", "16:00 - 20:00", "20:00 - 24:00"],
y: [20, 14, 23,12, 18, 29],
name: '1',
type: 'bar'
}
The chart is not showing but I’m not getting any error from the console.
These are my javascript functions (I took the filter function from this answer https://bit.ly/3jmISBP):
function _filter(list, predi) {
let newList = [];
for (let i = 0; i < list.length; i++) {
if (predi(list[i])) newList.push(list[i]);
}
return newList;
}
function addChartData(data){
const uniqueLabels = [1,2,3,4]
var traces = []
for (let label of uniqueLabels) {
x_axis = [];
y_axis = [];
labels = [];
let filteredList= _filter(data, (traceData) => traceData.level == label);
for (let item of filteredList) {
x_axis.push(item.fascia_oraria);
y_axis.push(item.tempo_medio);
labels.push(item.bin_level);
}
traces.push({
x: x_axis,
y: y_axis,
/*text: labels,*/
name: "Level " + label,
type: "bar"
});
}
var data = traces;
var layout = {
barmode: "group",
showlegend: true,
};
Plotly.newPlot('myChart', data, layout);
}
function getAPIData(){
$.ajax({
method: 'GET',
url: "../api/data",
beforeSend: function(){
$("#no_results").html("Loading data...");
},
success: function (data) {
addChartData(data);
},
error: function (data) {
console.log('Error');
}
});
}
And calling the function from HTML like this:
<script>
$(document).ready(function() {
getAPIData();
});
</script>
This approach worked for a simple bar chart, but not in this case.
Any idea about what I’m doing wrong?
Thank you