Skip to content Skip to sidebar Skip to footer

Plotly.js Create Stacked And Grouped Bar Chart

How to create barchart on Plotly.js with grouped and stacked bars? I need structure like that: Barchart with stacked and grouped charts

Solution 1:

It is possible to create a grouped-and-stacked bar chart in Plotly.js by creating each group as a subplot. It's not as simple as setting a top-level feature like 'barmode': 'stacked+grouped' but because it's more elemental it offers more options.

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

Here each subplot references a shared common yaxis and its own xaxis. Each xaxis gets a "domain" which here means a portion of the overall bottom axis width. Here the first group gets [0.0, 0.33], the second [0.34, 0.66] and the third [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'
    }
  }
);

Post a Comment for "Plotly.js Create Stacked And Grouped Bar Chart"