2014-11-16 71 views
0

我似乎無法找到將數據中的字符串添加到我的圈子的方法。 引用文本的代碼不起作用,也不會產生錯誤。 有什麼想法? 非常感謝你:)將文字添加到d3中的圓圈

 //Create circles    
     var circle=svg.append("g") 
      .attr("class", "circles") 
      .selectAll("circle") 
      .data(data) 
      .enter() 
      .append("circle") 
      .attr("cx", w/2) 
      .attr("cy", h/2) 
      .attr("r", 4) 
      .transition() 
      .duration(2000) 
      .attr("cx", function(d) { 
       return xScale(d.accountancy); 
      }) 
      .attr("cy", function(d) { 
       return yScale(d.income); 
      }) 
      .transition() 
      .duration(2000) 
      .attr("r", function(d) { 
       return d.income/radiusOffset; 
      }) 
      .attr("fill",function(d){ 
       if(d.accountancy<0){ 
        return "#DD2626"; 
       } 
       return "#4CA64C"; 
      }); 

      //create text 
     var text=svg.append("g").selectAll("text") 
        .data(data) 
        .enter() 
        .append("text") 
        .attr("x", function(d) { 
            return xScale(d.accountancy); 
           }) 
        .attr("y",function(d) { 
            return xScale(d.income); 
           }) 
        .attr("font-size","15px") 

      //Create X axis 
     svg.append("g") 
      .attr("class", "x axis") 
      .attr("transform", "translate(0," + (h - padding + 5) + ")") 
      .call(xAxis); 

     //Create Y axis 
     svg.append("g") 
      .attr("class", "y axis") 
      .attr("transform", "translate(" + (padding - 5) + ",0)") 
      .call(yAxis); 

    </script> 
</body> 

回答

0

您還沒有指定任何文字文本中的變量顯示。你所要做的就是用text給文本一些值,如;

.text(function (d) { return d.sometext; }); 

你可以看到一個例子,這個fiddle

0

工作需要創建每圈<g>元素,其中將包括您的<circle>和你<text>元素。例如:

//Creating the groups 
    var circles = svg.selectAll("g.circles"); 

    //Adding circles to the groups 
    circles = circles.data(data) 
      .enter() 
      .append("g") 
      .classed("circles", true); 

    circles.append("svg:circle") 

    //Styling the circles. 
    circles.selectAll("circle") 
     .attr("cx", w/2) 
     .attr("cy", h/2) 
     .attr("r", 4); 

    //Adding text labels to the groups 
    circles.append("text"); 

    //Styling text 
    circles.selectAll("text") 
      .text("Put your text stuff here") 
      .attr("font-family", "Courier") 
      .attr("fill", "black") 
      .style("opacity", "0.8") 
      .attr("font-size", "0.8em") 
      .attr("text-anchor", "middle"); 

可能有更優雅/簡潔的方法來做到這一點,但這在過去對我來說很合適。另請參閱此example by Mike Bostock

0

.attr( 「Y」,函數(d){ 返回xScale等(d.income);

問題是這裏..我用於Y斧XScale處理器,以及... 改變(d){ return yScale(d.income);