2016-04-30 59 views
0

我试图使用D3.js向散点图的每个圆添加一个标签,但无法弄清楚。在D3散点图上添加标签圈

这里是代码:https://jsfiddle.net/8e7qmzw8/;我想将属性“name”添加到每个圆圈(内部或外部)。

var data = [ 
    {"x": -123, "y": 63, "r": 37, "c": "#50C2E3", "name": "A"}, 
    {"x": 71, "y": 0, "r": 15, "c": "#50C2E3", "name": "B"}, 
    {"x": 3845, "y": 77, "r": 15, "c": "#50C2E3", "name": "C"}, 
    {"x": 3176, "y": 90, "r": 15, "c": "#50C2E3", "name": "D"}, 
    {"x": -17, "y": 56, "r": 15, "c": "#50C2E3", "name": "D"}, 
    {"x": 1357, "y": 58, "r": 15, "c": "#50C2E3", "name": "E"}, 
    {"x": 7684, "y": 75, "r": 15, "c": "#50C2E3", "name": "F"} 
]; 

var width = 500; 
var height = 500; 

var margin = { 
    top: 40, 
    right: 40, 
    bottom: 40, 
    left: 40 
}; 

var x = d3.scale.linear().range([0, width]); 
var y = d3.scale.linear().range([height, 0]); 

var minX = _(data).orderBy('x').first().x; 
var maxX = _(data).orderBy('x').last().x; 

x.domain([minX - 500, maxX + 500]); 
y.domain([0, 100]); 

var xAxis = d3.svg.axis() 
     .scale(x) 
     .orient("bottom"); 

var yAxis = d3.svg.axis() 
     .scale(y) 
     .orient("left"); 

var svg = d3 
     .select("#d3") 
     .append("svg") 
     .attr("width", width + margin.left + margin.right) 
     .attr("height", height + margin.top + margin.bottom) 
     .append("g") 
     .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); 

svg.append("g") 
     .attr("class", "x axis") 
     .attr("transform", "translate(" + 0 + "," + height/2 + ")") 
     .call(xAxis); 

svg.append("g") 
     .attr("class", "y axis") 
     .attr("transform", "translate(" + width/2 + "," + 0 + ")") 
     .call(yAxis) 
     .append("text"); 

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

有什么想法?

回答

3

这里的结果:https://jsfiddle.net/8e7qmzw8/1/

我包你的圈子和文本一<g>内侧:

var gdots = svg.selectAll("g.dot") 
      .data(data) 
      .enter().append('g'); 

然后把你的文字与<g>内圆一起。

圈:

gdots.append("circle") 
      .attr("class", "dot") 
      .attr("r", function (d) { 
       return d.r; 
      }) 
      .attr("cx", function (d) { 
       return x(d.x); 
      }) 
      .attr("cy", function (d) { 
       return y(d.y); 
      }) 
      .style("fill", function (d) { 
       return d.c; 
      }); 

和文字:

gdots.append("text").text(function(d){ 
        return d.name; 
       }) 
       .attr("x", function (d) { 
        return x(d.x); 
       }) 
       .attr("y", function (d) { 
        return y(d.y); 
       }); 

当然你也可以与x玩和y的,你甚至可以添加dx和dy ATTRS,使文字更居中或地方你想让他们成为。