-
Notifications
You must be signed in to change notification settings - Fork 0
3.5 Making the stacked bar chart
Now that the data was transformed i could go on making the stacked bar chart. Since the data transformation was done with d3's stack function in mind i could now go ahead and use that:
The stack function is used in the following manner:
//stack the smokingtools
let stack = d3.stack()
.keys(["hasjpijpen", "tabakspijpen", "waterpijpen", "pijpen (rookgerei)", "opiumpijpen"])
.order(d3.stackOrderAscending)
.offset(d3.stackOffsetNone);
//give the stack function the cleaned data
let series = stack(data)this produces the following:
[[0, 1], [0, 1], [0, 0], [0, 0], [0, 0], data: {…}] // hasjpijpen
[[1, 1], [1, 3], [0, 103], [0, 0], [0, 0], data: {…}], // waterpijpen
[[1, 3], [3, 3], [103, 249], [0, 0], [0, 0], data: {…}], // opiumpijpen
[[3, 14], [3, 54], [249, 442], [0, 2], [0, 39], data: {…}] // tabakspijpen
[[14, 95], [54, 375], [442, 635], [2, 11], [39, 69], data: {…}] // pijpen: (rookgerei)- index[0] of each array are the values that make up for origin Amerika
- index[1] of each array are the values that make up for origin Afrika
- index[2] of each array are the values that make up for origin Azië
- index[3] of each array are the values that make up for origin Eurazië
- index[4] of each array are the values that make up for origin Oceanië
In order to render bars out of this, i had to do two data joins. Mike bostock's used join() instead of enter(). I did some research onthis and found out that unlike enter() join could be chained multiple times, which made more sense than the old enter() function. So the first datajoin is the array that hold everything, a group is appended for each array and these groups get a color that based on the key(which in this case are the categories of smoking tools). Next there is a the rects get selected and joined with each array item. In order to normalize the width of the bars the second array value has to be subtracted from the first one.
the code to render the bars:
g.append("g")
.selectAll("g")
.data(series)
.join("g")
.attr("fill", d => color(d.key))
.selectAll("rect")
.data(d => d)
.join("rect")
.attr("y", d => yScale(d.data.origin))
.attr("x", d => xScale(d[0]))
.attr("height", yScale.bandwidth())
.attr("width", d => xScale(d[1]) - xScale(d[0]))