简体   繁体   English

如何使 react + d3 堆积条形图分组?

[英]How to make a react + d3 stacked bar chart grouped?

I am using react + d3 to create a stacked and grouped bar chart, I made it stacked but couldn't find how to make it grouped also?我正在使用 react + d3 创建一个堆叠和分组的条形图,我将其堆叠但找不到如何将其分组?

I want something like this image我想要这样的图片

在此处输入图片说明

data looks like:数据看起来像:


    const data = [
      {
        name: "Brand 1",
        Affiliate: 10,
        Social: 20,
        Media: 30
      },
      {
        name: "Brand 2",
        Affiliate: 20,
        Social: 40,
        Media: 60
      },
      {
        name: "Brand 3",
        Affiliate: 30,
        Social: 45,
        Media: 80
      },
      {
        name: "Brand 4",
        Affiliate: 40,
        Social: 60,
        Media: 100
      },
      {
        name: "Brand 5",
        Affiliate: 50,
        Social: 80,
        Media: 120
      }
    ];


and the part that generate stack looks like:生成堆栈的部分如下所示:


    const stackGenerator = stack().keys(keys);
    const layers = stackGenerator(data);

you can check the full code and demo in demo您可以在演示中查看完整代码和演示

any help to make it stacked + grouped will be appreciated任何使其堆叠+分组的帮助将不胜感激

Based on this example , something like this should work: you can find the entire example here .基于这个例子,这样的事情应该可以工作:你可以在这里找到整个例子。

const data = [
  {
    name: "Brand 1",
    type: 1,
    Affiliate: 10,
    Social: 20,
    Media: 30
  },
  {
    name: "Brand 1",
    type: 2,
    Affiliate: 20,
    Social: 40,
    Media: 60
  },
  {
    name: "Brand 2",
    type: 1,
    Affiliate: 30,
    Social: 45,
    Media: 80
  },
  {
    name: "Brand 3",
    type: 1,
    Affiliate: 40,
    Social: 60,
    Media: 100
  },
  {
    name: "Brand 3",
    type: 2,
    Affiliate: 50,
    Social: 80,
    Media: 120
  }
];

Make two nested axes:制作两个嵌套轴:

    const x0Scale = scaleBand()
      .domain(data.map((d) => d.name))
      .range([0, width])
      .padding(0.46);
    const x1Scale = scaleBand()
      .domain(data.map((d) => d.type))
      .rangeRound([0, x0Scale.bandwidth()])
      .padding(0.12);

and make the width of the bar dependent on the width of the smallest axis:并使条的宽度取决于最小轴的宽度:

.attr("x", (sequence) => x0Scale(sequence.data.name)
                         + x1Scale(sequence.data.type))
.attr("width", x1Scale.bandwidth())

This yields the following picture:这产生了以下图片:

结果图像

The only downside is that the solution assumes that every group has the same members - otherwise it doesn't draw them, as you can see from the gap to the right of "Brand 2".唯一的缺点是该解决方案假设每个组都有相同的成员 - 否则它不会吸引他们,正如您从“品牌 2”右侧的间隙中看到的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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