D3 Horizontal Bar Chart Will Not Transition To New Dataset
I'm working on a d3.js horizontal bar graph (http://bl.ocks.org/juan-cb/ab9a30d0e2ace0d2dc8c) which updates/transitions based on user selections. Currently, I have added labels to
Solution 1:
Here is my suggestion: since you're appending both rectangles and texts elements to the <g>
(groups), your enter-update-exit pattern should apply to the groups, not to the rectangles and texts:
var bar = svg.selectAll(".bar")
.data(dataset, function(d) {
return d.label;
});
var barExit = bar.exit().remove();
var barEnter = bar.enter()
.append("g")
.attr("class", "bar");
In fact, as your datasets always have 6 categories, you don't even need all this (the code could be substantially shorter).
Here is your updated fiddle: https://jsfiddle.net/2523onr3/
PS I took the liberty to make the bars growing from left to right, not from right to left. If that's incorrect, just change the x
and width
attributes.
Solution 2:
I'd be interested in the pros and cons versus this approach?
https://jsfiddle.net/sjp700/2523onr3/2/
bar = svg.selectAll(".bar")
.data(dataset)
bar_g = bar.enter()
.append("g")
.attr("class", "bar")
.transition()
.attr("transform", function (d) { return"translate(" + x(0) + "," + y(d.label) + ")"; });
svg.selectAll(".bar")
.append("rect")
.attr("class", "rectband");
svg.selectAll(".bar")
.append("text")
.attr("class", "textband");
bar.selectAll(".textband")
.attr("transform", function (d) { return"translate(" + x(d.value) + "," + 0 + ")"; })
.attr("y", 30)
.attr("dy", ".35em")
.style("fill", "black")
.text(function (d) { return d.value; });
bar.selectAll(".rectband")
.attr("width", function (d) { returnx(d.value); })
.attr("height", y.rangeBand());
Post a Comment for "D3 Horizontal Bar Chart Will Not Transition To New Dataset"