d3.js: How to add labels to scatter points on graph

tmnt-rafael picture tmnt-rafael · Sep 4, 2012 · Viewed 13.1k times · Source

I am trying to add labels to the scatter points on this graph: http://bost.ocks.org/mike/d3/workshop/dot-chart.html

I thought that modifying this code a little bit would work, but it didn't:

svg.selectAll(".dot")
  .append("text")
  .text("fooLabelsOfScatterPoints");

Answer

tmnt-rafael picture tmnt-rafael · Sep 4, 2012

Mike Robinson, your example helped.

For those who are wondering, here is what I did:

I removed:

svg.selectAll(".dot")
  .data(data)
  .enter().append("circle")
  .attr("class", "dot")
  .attr("cx", function(d) { return x(d.x); })
  .attr("cy", function(d) { return y(d.y); })
  .attr("r", 12);

and added:

var node = svg.selectAll("g")
                .data(data)
                .enter()
                .append("g");

node.append("circle")
  .attr("class", "dot")
  .attr("cx", function(d) { return x(d.x); })
  .attr("cy", function(d) { return y(d.y); })
  .attr("r", 12);

node.append("text")
  .attr("x", function(d) { return x(d.x); })
  .attr("y", function(d) { return y(d.y); })
  .text("fooLabelsOfScatterPoints");

I appended "text" tags onto "g" tags, as opposed to appending "text" tags onto "circle" tags.