9

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");
paxRoman
  • 2,064
  • 3
  • 19
  • 32
lanadelrey
  • 441
  • 1
  • 4
  • 10
  • 3
    Have you looked at this example: http://mbostock.github.com/d3/ex/bubble.html, and it's source: http://mbostock.github.com/d3/ex/bubble.js – Mike Robinson Sep 04 '12 at 19:26
  • Mike, from looking at your example, I think I have to append tags onto tags, as opposed to appending tags onto tags. I'll try it out now. – lanadelrey Sep 04 '12 at 19:41

2 Answers2

16

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.

lanadelrey
  • 441
  • 1
  • 4
  • 10
  • @MikeRobinson I have a similar problem but with a different version of bubbles..that is bubbles' radius varies while I move the slider..I want to add text in those bubbles as well..can you help a bit? – user2480542 Jul 18 '13 at 20:04
0

When I tried the node solution, some of my data disappeared (?), so I just added a new class called "dodo" which worked for me:

svg.selectAll(".dot")
  .data(data)
 .enter().append("circle")
  .attr("class", "dot")
  .attr("r", 3.5)
  .attr("cx", function(d) { return x(d.time); })
  .attr("cy", function(d) { return y(d.place); })
  .style("fill", function(d) { return color(d.species); });

svg.selectAll(".dodo")
  .data(data)
 .enter().append("text")
  .attr("class", "dodo")
  .attr("x", function(d) { return x(d.time); })
  .attr("y", function(d) { return y(d.place); })
  .attr("dx", ".71em")
  .attr("dy", ".35em")
  .text(function(d) { return d.name;});
ezChx
  • 4,024
  • 1
  • 19
  • 16