传奇D3圈包图

时间:2013-12-04 03:49:09

标签: javascript svg d3.js legend circle-pack

我需要为气泡/圆形包装图创建一个图例。我在圆圈内显示值。我需要名字作为传说。例如,在下面提供的数据中,如果值为60,我需要在图例中使用该名称“Petrol”。我怎么能实现它?

段:

var diameter = 200,
    format = d3.format(",d"),
    color = ["#7b6888", "#ccc", "#aaa", "#6b486b"];

var bubble = d3.layout.pack().size([diameter, diameter]);

var svg = d3.select("#bubbleCharts").append("svg")
    .attr("width", diameter + 10)
    .attr("height", diameter)
    .attr("class", "bubble");

d3.json("flare.json", function(error, root) {
    var node = svg.selectAll(".node")
        .data(bubble.nodes(classes(root))
        .filter(function(d) { return !d.children; }))
        .enter().append("g")
        .attr("class", "node")
        .attr("transform", function(d) { return "translate(" + d.x + 20 + "," + d.y + ")"; });

    node.append("circle").attr("r", function(d) { return d.r+ 7; })
        .style("fill", function(d,i) { return color[i];} );

    node.append("text").attr("dy", ".3em").style("text-anchor", "middle")
        .text(function(d) { return d.value+"%"; });
});

function classes(root) {
    var classes = [];

    function recurse(name, node) {
        if (node.children) 
             node.children.forEach(function(child){
                  recurse(node.name, child); 
             });
        else 
            classes.push({packageName: name, value: node.value});
     }

     recurse(null, root);
     return {children: classes};
}

var legend = d3.select("#bubbleChart").append("svg")
    .selectAll("g").data(node.children).enter().append("g")
    .attr("class","legend")
    .attr("width", radius)
    .attr("height", radius * 2)
    .attr("transform", function(d, i) {return "translate(" + i *10 + "0" + ")"; });


legend.append("rect").attr("width", 18).attr("height", 10)
    .style("fill", function(d, i) { return color[i];});

legend.append("text").attr("x", 24).attr("y", 5).attr("dy", ".35em")
    .text(function(d) { return d; });

我的数据:

  {
  "name": "Spending Activity",
   "children": [
  {"name": "Petrol", "value": 10},
  {"name": "Travel", "value": 60},
  {"name": "Medical", "value": 25},
  {"name": "Shopping", "value": 5}
    ]
   }

我如何从json获取值并创建一个图例?感谢。

1 个答案:

答案 0 :(得分:1)

您可以简单地遍历数据集并添加这些值:

legend.selectAll("circle").data(data.children)
      .enter()
      .append("circle")
      .attr("cy", function(d,i) { return (i+1) * 10; })
      .attr("r", function(d) { return d.r+ 7; })
      .style("fill", function(d,i) { 
        return color[i];
      });
legend.selectAll("text").data(data.children)
      .enter()
      .append("text")
      .attr("transform", function(d,i) {
        return "translate(10," + ((i+1) * 10) + ")";
      });