Skip to content Skip to sidebar Skip to footer

Chartjs - Stacked Bar Chart With Groups - How To Create Second X-axis With Stack Id

I have a chart.js grouped bar chart (grouped by the stack id), what I want to do, is add another x-axis, which will show the stack id, the closest I got was doubling the labels, so

Solution 1:

To have the additional labels aligned with the stack group bars, you can define the option categoryPercentage: 1 on each dataset.

For further information, consult the chapters Dataset Configuration and barPercentage vs categoryPercentage of the Chart.js bar documentation.

Further you'll have to define several x-axes as shown in your amended code below.

newChart('c', {
  type: 'bar',
  data: {
    labels: ["1.1.2021", "2.1.2021"],
    datasets: [{
        label: 'First Time Visitor England',
        data: [10, 3],
        stack: "first-time-visitors",
        backgroundColor: "#f5a0a7",
        categoryPercentage: 1
      },
      {
        label: 'Repeating Visitors England',
        data: [20, 6],
        stack: "repeat-visitors",
        backgroundColor: "#e75177",
        categoryPercentage: 1
      },
      {
        label: 'First Time Visitor Sweden',
        data: [7, 0],
        stack: "first-time-visitors",
        backgroundColor: "#924565",
        categoryPercentage: 1
      },
      {
        label: 'Repeating Visitors Sweden',
        data: [9, 16],
        stack: "repeat-visitors",
        backgroundColor: "#2979a7",
        categoryPercentage: 1
      }
    ]
  },
  options: {
    tooltips: {
      mode: 'x'
    },
    scales: {
      xAxes: [{
          ticks: {
            display: false
          }
        },
        {
          type: 'category',
          offset: true,
          labels: ['first-time-visitors', 'repeat-visitors', 'first-time-visitors', 'repeat-visitors'],
          gridLines: {
            display: false
          }
        },
        {
          offset: true,
          gridLines: {
            display: false
          }
        }
      ],
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script><canvasid="c"width="400"height="200"></canvas>

Post a Comment for "Chartjs - Stacked Bar Chart With Groups - How To Create Second X-axis With Stack Id"