Reputation: 1879
I have a dictionary called dict that looks as follows:
var dict = {
'Ex': 6,
'C': 6,
'blue': 2,
'car': 2,
'yellow': 2,
'X': 4,
'X3': 2
};
I would like to plot an histogram of it, with the keys as the labels of the horizontal axis and the values of the dictionary that are the frecuency as the vertical axis, I tried:
<canvas id="myChart" width="100" height="100"></canvas>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [],
datasets: [{
label: '# Frecuencies Words',
data: [],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
However the problem is that I am not sure of how to proceed to use the values of the dictionary to perform the graph, I would like to appreciate any suggestion to achieve this, I built the following jsfiddle to explain better the situation: https://jsfiddle.net/xbbc677o/
Upvotes: 0
Views: 1226
Reputation: 7459
You're not doing bad, all you need now is to map that object into the data
and label
fields. Let's begin with labels
Object.keys(dict)
returns an array of all the keys from dict
So we put
labels: Object.keys(dict)
Now we need the values for the data
array, with Object.keys
and map
we can do it easily, we use Object.keys
to get an array of all the keys in dict
and then map
to get each value from it's key, like this:
data: Object.keys(dict).map(function (key) { return dict[key]; })
Both Object.keys
and map
are part of the ECMAScript 5 specification, so this wont work on ES3 (IE 8 or lower), but you can get pollyfils for both of those functions:
Upvotes: 3