I am using mbostock's bar chart. The code is nearly the same. Instead of letter and frequency, I have name and value respectively. I want to display the value of each data on the bar. I tried adding this at the end.
svg.selectAll(".bar").append("text")
.attr("x", height/2)
.attr("y", function(d) { return y(d.value) - 3; })
.text(function(d) { return d.value; });
But that doesn't seem to work at all. So what have I messed up?
You are appending the text
to rect
elements -- this isn't valid in SVG and the text won't show up. Instead, append the text
either to a g
element or the top-level SVG:
svg.selectAll("text.bar")
.data(data)
.enter().append("text")
.attr("class", "bar")
.attr("text-anchor", "middle")
.attr("x", function(d) { return x(d.letter); })
.attr("y", function(d) { return y(d.frequency) - 10; })
.text(function(d) { return d.frequency; });
Complete demo here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With