Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3.json pass data to d3.svg.arc()

Tags:

svg

d3.js

charts

I'm not strong JS user, but I want make "Nightingale chart" like this: http://windhistory.com/station.html?KHKA I have that code:

<!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>

On jsfinddle: http://jsfiddle.net/lmasikl/gZ62Z/

my 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}
]

But my script draw only one arc. Can anybody help to solve this problem?

like image 875
lmasikl Avatar asked Nov 27 '12 15:11

lmasikl


1 Answers

You may want to read Thinking With Joins. The D3 pattern for adding data-driven elements is to create a selection with selectAll, then set the data with data, then append the element, to the .enter() selection. So

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

needs to be

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

See updated fiddle: http://jsfiddle.net/gZ62Z/1/

like image 100
nrabinowitz Avatar answered Sep 23 '22 16:09

nrabinowitz