Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bar chart show values on top

Tags:

d3.js

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?

like image 879
Sawal Maskey Avatar asked Jan 11 '23 03:01

Sawal Maskey


1 Answers

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.

like image 78
Lars Kotthoff Avatar answered Feb 08 '23 11:02

Lars Kotthoff