Stacked Bar Chart With Negative Json Data
Solution 1:
In the example you linked, the original data is grouped by band type. Your data is grouped by set - that is, in the original each color band is grouped in the data array. In your data, each stack of bands is a group of objects in the data array.
If you want to reuse the original code, we need to translate the data (90 degrees) like so:
var initialData = [{x:"abc", y1:"3", y2:"4", y3:"10"},
{x:"abc2", y1:"6", y2:"-2", y3:"-3" },
{x:"abc3", y1:"-3", y2:"-9", y3:"4"}]
var data = ["y1","y2","y3"].map(
function(v){
return initialData.map(function(d){
return {y: +d[v]};
});
});
Then, most of the original code can be used as-is.
Another part which you can adapt is the domain for the x-scale
x = d3.scale.ordinal()
.domain(['abc','abc2','abc3'])
.rangeRoundBands([margin,w-margin], .1)
The group names are hard coded, but you have them in your objects as "x".
Instead, we can automatically use the x value of each object as the label for each set:
x = d3.scale.ordinal()
.domain(initialData.map(function(d){return d.x}))
.rangeRoundBands([margin,w-margin], .1)
Putting it all together, with some extra values: http://jsfiddle.net/fLMAZ/1/
The other option is to rewrite the code to bind the data as-is, but you will need to understand how the stacked bar chart is built and then adapt it to your original JSON.
Solution 2:
You have a couple of options:
- Is to provide the data from the server side to make it look like the JSON structure that graph likes.
- You can parse through your JSON on the client side and make a new JSON
- You can modify the graph chart such that it will work with your JSON
Post a Comment for "Stacked Bar Chart With Negative Json Data"