简体   繁体   中英

Adding multiple groups to radial D3 chart

Sorry if the title is misleading. Basically I have the following d3 chart:

d3 径向条形图

Which is based on an array of 5 elements, each one containing 3 separate values. As you can see, the radial chart is grouped into 5 sections (with a gap) and then each section contains the 3 separate values as bar charts.

Here is a js fiddle: https://jsfiddle.net/kpu5o7v2/ And my data:

[
        {
            index: 0,
            name: "John",
            red: 35,
            green: 16,
            blue: 56
        },
        {
            index: 1,
            name: "Spencer",
            red: 12,
            green: 34,
            blue: 8
        },
        {
            index: 2,
            name: "Alice",
            red: 6,
            green: 6,
            blue: 70
        },
        {
            index: 3,
            name: "Cat",
            red: 12,
            green: 80,
            blue: 1
        },
        {
            index: 4,
            name: "Dave",
            red: 80,
            green: 1,
            blue: 2
        }
    ]

What I want to know, is how can I also add sections to correspond to the new_data.name value? ie. the wider groups. So I can then style them indivdually So, for example, for "John":

  • start angle is 0
  • end angle is the same end angle as John's blue section
  • radius is some number > largest subsection.

Below is an example (if you were to give this group a stroke):

在此处输入图像描述

I figured out the answer to this:

  • We need to add a new g to the SVG with the same new_data again
  • Create a new arc object for the names ("John", "Spencer", etc) instead of the keys ("red", "green", "blue")
  • Radius is y(ymax) where ymax is the largest value in all the data
  • start angle is just x0(name) (on a scale of 0 to 2PI)
  • end angle is the same as above + the width. Which is circumference/number of names.

  let arc2 = d3.arc()
    .innerRadius(innerRadius)
    .outerRadius((d) => {
      return y(ymax);
    })
    .startAngle(d => {
      return x0(d.name)
    })
    .endAngle(d => {
      //let circumference = 2* Math.PI;
      //let bandwidth = circumference/names.length;
      let endAngle = x0(d.name) + (x0.bandwidth() * 0.8);
      return endAngle;
    })
    .padAngle(0.01)
    .padRadius(innerRadius);

  svg.append("g")
    .selectAll("path")
    .data(new_data)
    .enter()
    .append("path")
    .attr('fill', d => {
      return "none";
    })
    .attr("stroke", "#333")
    .attr("stroke-width", 2)
    .attr("d", arc2);

New JS Fiddle: https://jsfiddle.net/kpu5o7v2/1/

Result: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM