Reputation: 1725
Is it possible to build a stacked bar chart in D3 with different stacked levels?
I've been reading about it but cud only find examples which has same stacked levels.
In other words, Instead of this JSON -
var layers = [
{
"name": "apples",
"values": [
{ "x": 0, "y": 11},
{ "x": 1, "y": 10},
{ "x": 2, "y": 10}
]
},
{
"name": "oranges",
"values": [
{ "x": 0, "y": 9},
{ "x": 1, "y": 9},
{ "x": 2, "y": 9}
]
}
];
Can we create a bar chart with -
var layers = [
{
"name": "apples",
"values": [
{ "x": 0, "y": 11},
{ "x": 1, "y": 10},
{ "x": 2, "y": 10}
]
},
{
"name": "oranges",
"values": [
{ "x": 0, "y": 9}
]
}
];
I read - https://bl.ocks.org/mbostock/3886208
https://bl.ocks.org/mbostock/1134768
https://github.com/mbostock/d3/wiki/Stack-Layout
Upvotes: 1
Views: 735
Reputation: 1046
This is fairly easy to do, depending on how you design your loading of data into the chart.
Essentially the process would be:
data()
function with the layers variable, which allows you to then work with each data set individuallyg
element using the enter()
function of the result of step 1data()
again, this time using the values
of the attached data (.data(function(d){return d.values;})
)enter()
function of the result of step 3 to generate the barsNote that to get things to actually stack you will need to keep track of the current stacked height of each x position. All you have to do is generate an array of zeroes and update the value at index d.x
when setting the rectangle's y
attribute.
Fiddle showing a quick sample. To make this a fully working example, you'll have to add axes/scales and all the extra things.
Upvotes: 1