如何将文本变量用于标签d3图形

时间:2015-07-31 03:02:18

标签: d3.js

我正在学习d3,我使用“dataset”变量作为图形的值, 我希望使用dataset.nombre值标记d3图形,但我只能使用dataset.numbers,这是一个简化的代码版本:

<body>
    <div id="container2"></div>
<script>

 var dataset = {
  numbers: [15, 3, 10, 2, 14,17,1],
  nombre:["a","b","c","d","e","f","g"]
};

var color = d3.scale.category20();

var pie = d3.layout.pie()
    .sort(null);

var piedata = pie(dataset.apples);

var arc = d3.svg.arc()
    .innerRadius(radius - 100)
    .outerRadius(radius - 50);

var svg = d3.select("#container2").append("svg")
    .attr("width", width)
    .attr("height", height)
    .append("g")
    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var path = svg.selectAll("path")
    .data(piedata)
  .enter().append("path")
    .attr("fill", function(d, i) { return color(i); })
    .attr("d", arc);

svg.selectAll("text").data(piedata)
    .enter()
    .append("text")
    .attr("text-anchor", "middle")
    .attr("x", function(d) {
        var a = d.startAngle + (d.endAngle - d.startAngle)/2 - Math.PI/2;
        d.cx = Math.cos(a) * (radius - 75);
        return d.x = Math.cos(a) * (radius - 20);
    })
    .attr("y", function(d) {
        var a = d.startAngle + (d.endAngle - d.startAngle)/2 - Math.PI/2;
        d.cy = Math.sin(a) * (radius - 75);
        return d.y = Math.sin(a) * (radius - 20);
    })
    .text(function(d) { return d.value; }) 
    .each(function(d) {
        var bbox = this.getBBox();
        d.sx = d.x - bbox.width/2 - 2;
        d.ox = d.x + bbox.width/2 + 2;
        d.sy = d.oy = d.y + 5;
    });

svg.append("defs").append("marker")
    .attr("id", "circ")
    .attr("markerWidth", 6)
    .attr("markerHeight", 6)
    .attr("refX", 3)
    .attr("refY", 3)
    .append("circle")
    .attr("cx", 3)
    .attr("cy", 3)
    .attr("r", 3);

svg.selectAll("path.pointer").data(piedata).enter()
    .append("path")
    .attr("class", "pointer")
    .style("fill", "none")
    .style("stroke", "black")
    .attr("marker-end", "url(#circ)")
    .attr("d", function(d) {
        if(d.cx > d.ox) {
            return "M" + d.sx + "," + d.sy + "L" + d.ox + "," + d.oy + " " + d.cx + "," + d.cy;
        } else {
            return "M" + d.ox + "," + d.oy + "L" + d.sx + "," + d.sy + " " + d.cx + "," + d.cy;
        }
    });

    </script>

</body>

1 个答案:

答案 0 :(得分:1)

理想情况下,您将对象而不是数字作为传递给饼图布局的数据;那么你就可以直接使用这些数据了。在您的情况下,您仍然可以使用索引:

.text(function(d, i) { return dataset.nombre[i]; })

完整演示here