var data = [{
x: 'A',
y: 3
}, {
x: 'B',
y: 2
}, {
x: 'C',
y: 4
}, {
x: 'D',
y: 3
}];
var xScale = new Plottable.Scales.Category()
var yScale = new Plottable.Scales.Linear()
var xAxis = new Plottable.Axes.Category(xScale, "bottom");
var plot = new Plottable.Plots.Bar()
.addDataset(new Plottable.Dataset(data))
.x(function(d) {
return d.x;
}, xScale)
.y(function(d) {
return d.y;
}, yScale)
.animated(true)
.renderTo("svg#example");
The above code renders the plots properly, but when I rather use:
var data2 = {
'A': 2,
'B': 3,
'C': 4,
'D': 5,
}
var plot = new Plottable.Plots.Bar()
.addDataset(new Plottable.Dataset(data2))
.x(function(d) {
return d;
}, xScale)
.y(function(d) {
return data2[d];
}, yScale)
.animated(true)
.renderTo("svg#example");
it doesn't work. How do I parse the data in objects? Is it possible to display the bar chart in alphabetical order of categories in X. e.g. Sometimes while converting from object to array, the array unpacks in random order of keys sometimes making the first element of it belong to 'B' key.
Transform your object to an array. First, get the keys and second, combine them with the value to an array. If it is still not in order, you can sort the array.
var data = Object.keys(data2).map(function (key) { return [key, data2[key]]; });
Demo:
var data2 = {'A': 2, 'B': 3, 'C': 4, 'D': 5};
var data = Object.keys(data2).map(function (key) { return [key, data2[key]]; });
console.log(data);