adding class names to arcs from data in d3.layout.pie()

独自空忆成欢 提交于 2019-12-25 10:01:31

问题


I'm creating a pie chart from a JSON file. I wonder if there is a way I can take some names from the JSON file and assign them as class names of the arcs created by d3.layout.pie().

Here is an example I created: http://blockbuilder.org/jinlong25/532d889e01d02cef2d24

Essentially, I want to do something like the last line of code below:

var data = [
  {
    'name': 'apple',
    'value': 250
  },
  {
    'name': 'banana',
    'value': 100
  },
  {
    'name': 'orange',
    'value': 150
  }
];

var arcs = svg.selectAll('g.arc')
              .data(pie(data.map(function(d) { return d.value; })))
              .enter().append('g')
              .attr('transform', 'translate(70, 70)')
              .attr('class', function(d) { return d.name; };

but since the data has been transformed by pie(), I wonder if there is anyway to add class names to the data generated by pie().

thanks!


回答1:


Some D3 layouts mutate the original dataset but others create a new dataset (like voronoi). In those cases, you can use the array position from the original dataset when working with the new dataset. So from your example:

var arcs = svg.selectAll('g.arc')
          .data(pie(data.map(function(d) { return d.value; })))
          .enter().append('g')
          .attr('transform', 'translate(70, 70)')
          .attr('class', function(d,i) { return data[i].name; };



回答2:


d3's layouts helpfully provide a .value() accessor which allows you to specify how get the value of the datum, instead of doing the data.map() operation. So, you could do:

var pie = d3.layout.pie().value(function(d) { return d.value; })

That way, your original datum is preserved in d.data.

So using that definition of pie, your code would change to this:

var arcs = svg.selectAll('g.arc')
          .data(pie(data))
          .enter().append('g')
          .attr('transform', 'translate(70, 70)')
          .attr('class', function(d) { return d.data.name; };

edit: added link the relevant documentation.



来源:https://stackoverflow.com/questions/34821449/adding-class-names-to-arcs-from-data-in-d3-layout-pie

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!