Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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");
like image 942
tmnt-rafael Avatar asked Sep 04 '12 15:09

tmnt-rafael


People also ask

How do you add a scatter plot to a label in R?

For the scatter plot on the left, we use plot() . Then we add the trend line with abline() and lm() . To add the labels, we have text() , the first argument gives the X value of each point, the second argument the Y value (so R knows where to place the text) and the third argument is the corresponding label.

How do I import D3 into Javascript?

Install D3 by running npm install d3 --save . Import D3 to App. js by adding import * as d3 from d3 . You need to use import * (“import everything”) since D3 has no default exported module.


1 Answers

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.

like image 192
tmnt-rafael Avatar answered Oct 16 '22 08:10

tmnt-rafael