1

I've recently been learning D3, and I've been playing around with this symbol map tutorial.

I've tried many things to get any of the data to display over the symbols as text, and I can't seem to figure out how to do it.

It seems like I need to add something along the lines of

.text(function(d) { return d.properties.population; })

somewhere. I've tried using .append or .selectAll in various places, but I can't get it to work.

4

1 回答 1

1

You can go about this in two ways you can use tooltips or place the text on the map. These's been plenty of discussion about tooltips such this google group conversation and the links with in including these biovisualise links: Simple tooltip and Tooltips as a helper. In the bl.ocks example you've pointed at using the simple tooltips option would require adding 2 lines of code as in:

  svg.selectAll(".symbol")
      .data(centroid.features.sort(function(a, b) { return b.properties.population - a.properties.population; }))
    .enter().append("path")
      .attr("class", "symbol")
      .attr("d", path.pointRadius(function(d) { return radius(d.properties.population); }))
    .append("title")
      .text(function (d) { return d.properties.name; });

To add text to the map you need to append some svg text elements. So you need to setup something similar to the symbol block above and calculate the x and y for the text. There are probably more elegant way's of doing this but this makes it very explicit what's going on. The x's and y's are calculated by path.centroid which returns the screen coordinates of your point.

svg.selectAll("text")
      .data(centroid.features).enter()    
    .append("text")
      .attr("x", function (d) { return path.centroid(d)[0]; })
      .attr("y", function (d) { return path.centroid(d)[1]; })
      .text(function (d) { return d.properties.name; }); 

Hope this helps

You can see both of them in action at this bl.ock.

于 2013-10-28T00:54:47.597 回答