d3.json将数据传递给d3.svg.arc()

时间:2012-11-27 15:22:26

标签: charts svg d3.js

我不是强大的JS用户,但我想制作像这样的“夜莺图”:http://windhistory.com/station.html?KHKA 我有那个代码:

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="d3.v2.js"></script>
    <style type="text/css">
        .arc{
            fill: pink;
            stroke: red;
        }
    </style>
  </head>
  <body>
    <div id="chart" class="chart"></div>
    <div id="table"></div>
    <script type="text/javascript">
      var svg = d3.select("#chart").append("svg").attr("width", 900).attr("height", 600);
      var pi = Math.PI;

      d3.json(
          'data.json',
          function(data){
            var arc = d3.svg.arc()
                .innerRadius(50)
                .outerRadius(function(d) { 
                    return (50 + d.value); 
                })
                .startAngle(function(d) { return ((d.time - 1) * 30 * pi / 180); })
                .endAngle(function(d) { return (d.time * 30 * pi / 180 ); });

            var chartContainer = svg.append("g")
                .attr('class', 'some_class')
                .attr("transform", "translate(450, 300)");

            chartContainer.append("path")
                .data(data)
                .attr("d", arc)
                .attr("class", "arc");
          }
      );
    </script>
  </body>
</html>

在jsfinddle上:http://jsfiddle.net/lmasikl/gZ62Z/

我的json:

[
    {"label": "January", "value": 150, "time": 1},
    {"label": "February", "value": 65, "time": 2},
    {"label": "March", "value": 50, "time": 3},
    {"label": "April", "value": 75, "time": 4},
    {"label": "May", "value": 150, "time": 5},
    {"label": "June", "value": 65, "time": 6},
    {"label": "July", "value": 50, "time": 7},
    {"label": "August", "value": 75, "time": 8},
    {"label": "September", "value": 65, "time": 9},
    {"label": "October", "value": 50, "time": 10},
    {"label": "November", "value": 75, "time": 11},
    {"label": "December", "value": 150, "time": 12}
]

但我的剧本只画了一个弧。有人可以帮忙解决这个问题吗?

1 个答案:

答案 0 :(得分:7)

您可能需要阅读Thinking With Joins。用于添加数据驱动元素的D3模式是使用selectAll创建选择,然后将数据设置为data然后将元素追加到{{1}选择。所以

.enter()

需要

chartContainer.append("path")
    .data(data)
    .attr("d", arc)
    .attr("class", "arc");

请参阅更新的小提琴:http://jsfiddle.net/gZ62Z/1/