Plotly.js创建堆叠和分组条形图

时间:2018-05-02 15:01:02

标签: javascript plotly plotly.js

如何使用分组和堆叠条形图在 Plotly.js 上创建条形图?我需要这样的结构: Barchart with stacked and grouped charts

1 个答案:

答案 0 :(得分:0)

通过将每个组创建为子图,可以在Plotly.js中创建分组堆积条形图。它并不像设置像barmode这样的顶级功能那么简单:'堆叠+分组'但因为它更具元素性,它提供了更多的选择。

请参阅https://community.plot.ly/t/combination-of-grouped-and-stacked-bar-chart/2154

这里每个子图都引用了一个共享的yaxis和它自己的xaxis。每个xaxis都有一个"域"这意味着整个底部轴线宽度的一部分。这里第一组获得[0.0,0.33],第二组[0.34,0.66]和第三组[0.67,1.0]

enter image description here

   Plotly.newPlot(
  "myDiv",
  [
    {
      x: ["A", "B", "C"],
      y: [0.3, 0.35, 0.4],
      type: "bar",
      name: "series 1a", 
      xaxis: 'x1',
      barmode: 'stack', 
      marker: {color: '#448'}
    },
    {
      x: ["A", "B", "C"],
      y: [0.6, 0.50, 0.40],
      type: "bar",
      name: "series 1b", 
      xaxis: 'x1',
      barmode: 'stack', marker: {color: '#88C'}
    },
    {
      x: ["A", "B", "C"],
      y: [0.1, 0.15, 0.20],
      type: "bar",
      name: "series 1c", 
      xaxis: 'x1',
      barmode: 'stack', 
      marker: {color: '#CCF'}
    },
    {
      x: ["A", "B", "C"],
      y: [0.3, 0.35, 0.4],
      type: "bar",
      name: "series 2a",
      xaxis: 'x2',     
      barmode: 'stack', marker: {color: '#080'}
    },
    {
      x: ["A", "B", "C"],
      y: [0.25, 0.15, 0.05],
      type: "bar",
      name: "series 2b",
      xaxis: 'x2',     
      barmode: 'stack', marker: {color: '#8c8'}
    },
    {
      x: ["A", "B", "C"],
      y: [0.45, 0.50, 0.55],
      type: "bar",
      name: "series 2c", 
      xaxis: 'x2',
      barmode: 'stack', marker: {color: '#CFC'}
    },
     {
      x: ["A", "B", "C"],
      y: [0.3, 0.35, 0.4],
      type: "bar",
      name: "series 3a", 
      xaxis: 'x3',
      barmode: 'stack', marker: {color: '#880'}
    },
    {
      x: ["A", "B", "C"],
      y: [0.6, 0.50, 0.40],
      type: "bar",
      name: "series 3b", 
      xaxis: 'x3',
      barmode: 'stack', marker: {color: '#CC8'}
    },
    {
      x: ["A", "B", "C"],
      y: [0.1, 0.15, 0.20],
      type: "bar",
      name: "series 3c", 
      xaxis: 'x3',
      barmode: 'stack', marker: {color: '#FFC'}
    },
  ],
  {
    barmode: "stack",
    yaxis: {tickformat: '%'},
    xaxis: {
      domain: [0, 0.33],
      anchor: 'x1', 
      title: 'Apples'
    },
    xaxis2: {
      domain: [0.33, 0.66],
      anchor: 'x2', title: 'Pears'
    },
    xaxis3: {
      domain: [0.67, 1.0],
      anchor: 'x3', title: 'Cherries'
    }
  }
);