2017-07-31 395 views
1

我想在SVG圈内追加文字 this例如在我的D3地图中。我见过很多类似的问题 - 我已经用它们来编写下面的代码,但不明白为什么它根本不显示。D3中的SVG圈内文字不显示

d3.json("https://raw.githubusercontent.com/d3/d3.github.com/master/world-110m.v1.json", function (error, topo) { 
      if (error) throw error; 

      gBackground.append("g") 
       .attr("id", "country") 
       .selectAll("path") 
       .data(topojson.feature(topo, topo.objects.countries).features) 
       .enter().append("path") 
       .attr("d", path); 


      gBackground.append("path") 
       .datum(topojson.mesh(topo, topo.objects.countries, function (a, b) { return a !== b; })) 
       .attr("id", "country-borders") 
       .attr("d", path); 


      console.log("Background Drawn"); 

      var point = gPoints.selectAll("circle") 
       .data(pointsData)  
       .enter()    
       .append("circle")  
       .attr("cx", function (d) { return d.location[0]; }) 
       .attr("cy", function (d) { return d.location[1]; }) 
       .attr("r", 10) 
       //Other attributes and mouseovers, etc 


      var texts = gPoints.selectAll("text") 
       .data(pointsData) 
       .enter() 
       .append("text") 
       .text(function (d) { return d.performance; }); 

      console.log("Points Drawn"); 

     }); 

回答

2

text没有出现的原因是因为:您没有指定需要出现的位置。

对于圆圈,你给cxcy,但没有文字。

一个更好的方法是做一团这样的:

var elem = gPoints.selectAll("g .myCircleText").data(pointsData) 
/*Create and place the "blocks" containing the circle and the text */ 
var elemEnter = elem.enter() 
    .append("g") 
    .classed("myCircleText", true) //add a class to the group 
    .attr("transform", function(d){return "translate("+d.location[0]+","+ d.location[1]+")"}) 

给一个如上图所示翻译(这样你就不需要给一个CX和CY组被翻译成团要求的点)。

现在做圈组内是这样的:

/*Create the circle for each block */ 
var circle = elemEnter.append("circle") 
    .attr("r", 10) 
    .attr("stroke","black") 
    .attr("fill", "white") 

现在使组

/* Create the text for each block */ 
elemEnter.append("text") 
    .attr("dx", function(d){return -20})//so that it comes 20 pixel from center. 
    .text(function(d){return d.performance}) 
+0

由于里面的文字! (它的作品,但不是与缩放功能) – Sbee