Search code examples
chart.jsstackedbarserieslineseries

Chart.js multiple series with same scale


I have a stacked bar chart with an unstacked line chart combo chart using Chart.js. I need the stacked bars and unstacked lines to appear on the same axis. It doesn't appear that I can do this, so I put them on different axes so that one could be stacked and the other not (e.g., overlay a capacity line over production of different parts). However, if they must be on different axes, then I need them to have the same scale. I could not find a way to force the axes to have the same scale automatically, so I am forced to try to compute my own scale and set them each to that. This isn't ideal and I would prefer if I could just use a setting to force them to use the same scale. Is this possible?

Here is a post that is basically the same question as I am: Chart.js place both series on same scale The only difference is that I need to stack my bar series which prevents me from using the same axes.


Solution

  • I might be misunderstanding what you are trying to do, but it is possible to create a stacked bar chart with an un-stacked line chart combo on the same axis.

    Here is an example configuration showing how do to it.

    var myChart = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [{
          type: 'line',
          label: 'Dataset 1',
          borderColor: window.chartColors.blue,
          borderWidth: 2,
          fill: false,
          data: [5, 3, 4, 10, 8, 9, 2]
        }, {
          type: 'bar',
          label: 'Dataset 2',
          backgroundColor: window.chartColors.red,
          stack: 'Stack 0',
          data: [2, 4, 1, 3, 7, 3, 6],
          borderColor: 'white',
          borderWidth: 2
        }, {
          type: 'bar',
          label: 'Dataset 3',
          backgroundColor: window.chartColors.green,
          stack: 'Stack 0',
          data: [7, 2, 4, 5, 6, 4, 2]
        }]
      },
      options: {
        responsive: true,
        title: {
          display: true,
          text: 'Chart.js Stacked Bar and Unstacked Line Combo Chart'
        },
        tooltips: {
          mode: 'index',
          intersect: true
        },
        scales: {
          xAxes: [{
            stacked: true,
          }]
        }
      }
    });
    

    Here is a working codepen example as well.