Reputation: 65
I'm trying to create grouped bar chart like in this example http://bl.ocks.org/kpq/6695897 with the difference that instead of 3 columns with 2 bars each I want 1 column with 3 bars.
I wrote code to create basic shapes but rectangles don't appear. Screen is just blank. I am not so experienced with d3 and also console doesn't show any error so I can't spot my mistake.
y0
, y1
and x1
are scales and they work fine.
Code:
var year = svg.selectAll(".g-year")
.data(nestedData)
.enter()
.append("g")
.attr("transform", function(d) { return "translate(0," + y0(d.key) +
")" })
.append("text")
.text(function(d) { return d.key; })
.attr("dy", 20)
.attr("dx", -100);
var metric = year.append('g')
.selectAll('.g-metric-bars')
.data(function (d) {
return d.values;
})
.enter()
.append('g')
.attr('class', 'g-metric-bars')
.attr('transform', function (d) {
return 'translate(0 ,' + y1(d.key) + ')';
})
.append('g')
.attr('class','bar')
.append('rect')
.attr('width', function(d){
return x1(d.value);
})
.attr('height', y1.bandwidth())
.attr('transform',function (d,i) {
return "translate(0," + y1.bandwidth() + ")";
})
.attr('fill', 'black');
Screen:
Upvotes: 2
Views: 387
Reputation: 102174
After appending a <text>
element, your year
selection is actually just a text selection:
var year = svg.selectAll(".g-year")
.data(nestedData)
.enter()
.append("g")
.attr("transform", function(d) { return "translate(0," + y0(d.key) +
")" })
.append("text")//from here on, a text selection
.text(function(d) { return d.key; })
.attr("dy", 20)
.attr("dx", -100);
And, since a <text>
element cannot hold groups (<g>
), you have the explanation for your blank screen.
The solution is simple: break your selection:
var year = svg.selectAll(".g-year")
.data(nestedData)
.enter()
.append("g")
.attr("transform", function(d) { return "translate(0," + y0(d.key) +
")" });
var foo = year.append("text")
.text(function(d) { return d.key; })
.attr("dy", 20)
.attr("dx", -100);
That way, year
is an enter selection containing <g>
elements.
Upvotes: 2