Chartjs-Draw stacked horizontal bar chart with Average line using ChartJS

0👍

The lines can be drawn using floating bars tied to the separate axis y2. To do so, you need to add another dataset as follows (I don’t exactly understand what values you want to display, hence I randomly chose 40, 65 and 55):

{
  label: "Lines",
  backgroundColor: "rgb(255, 0, 0)",
  data: [40, 65, 55].map(v => [v - 0.3, v + 0.3]),
  yAxisID: 'y2',
  order: -1
}

Further you must define a new scales option as shown below:

y2: {
  display: false
}

Please take a look at your amended runnable code and see how it works.

var data = {
  labels: ["January", "February", "March"],
  datasets: [{
      label: "Dogs",
      backgroundColor: "rgba(237, 192, 169)",
      data: [20, 10, 25]
    },
    {
      label: "Cats",
      backgroundColor: "rgba(253, 234, 175)",
      data: [70, 85, 65]
    },
    {
      label: "Birds",
      backgroundColor: "rgba(179, 211, 200)",
      data: [10, 5, 10]
    },
    {
      label: "Lines",
      backgroundColor: "rgb(255, 0, 0)",
      data: [40, 65, 55].map(v => [v - 0.3, v + 0.3]),
      yAxisID: 'y2',
      order: -1
    }
  ]
};

new Chart('myChart', {
  type: 'bar',
  data: data,
  options: {
    indexAxis: 'y',
    plugins: {
      legend: {
        display: false
      }
    },
    scales: {
      y: {
        stacked: true,
        grid: {
          display: false
        }
      },
      y2: {
        display: false
      },
      x: {
        stacked: true,
        beginAtZero: true,
        grid: {
          display: false
        }
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="myChart" height="100"></canvas>

Leave a comment