Search code examples
chart.jschartjs-2.6.0vue-chartjs

Drawing a mixed stacked horizontal bar/line in chartjs


I've looked at the docs/examples for chartjs, but does anyone know a way to do the following?

  • Create bars where the width (x-axis) is variable but the height is always full (aka the entire y-axis)?
  • There can be x number of those bars in a chart
  • Create a line that spans all the way across the x axis but can change it's y-axis (aka not a straight line, but a curvy one).

I have a crude drawing here where the yellow is the bars and the black is the line

I kinda got the first part down using stacked bars and swapping the axis, but the y-axis (the bars height) is only set to 1. That's a problem when trying to draw a curved line in mixed mode since there is only one y-axis point (instead of many y-axis points):

Here's another attempt that has multiple y-axis points, but I cannot control the bar widths:

If anyone can help (or at least tell me if I'm going in the right direction), it would be greatly appreciated!

Please see code in the jsfiddle link

Solution

  • It looks like this is the best solution:

    https://codepen.io/kurkle/pen/ExxdyXQ

    var ctx = document.getElementById("chart").getContext("2d");
    var chart = new Chart(ctx, {
      type: "horizontalBar",
      data: {
        labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
        datasets: [
          {
            label: "Bar1",
            data: [[2.5, 5.7]],
          },
          {
            label: "Bar2",
            data: [[6, 8]],
          },
          {
            label: "Bar3",
            data: [[9,10]],
          },
          {
            label: "Line",
            type: "line",
            backgroundColor: "rgb(75, 192, 192, 0.5)",
            borderColor: "rgb(75, 192, 192)",
            fill: false,
            tension: 0,
            data: [11, 10, 9, 8, 7, 6, 5, 4, 3, 2],
            yAxisID: "line"
          }
        ]
      },
      options: {
        datasets: {
          horizontalBar: {
            backgroundColor: "rgb(255, 99, 132, 0.5)",
            borderColor: "rgb(255, 99, 132)",
            borderWidth: 1,
            barPercentage: 1,
            categoryPercentage: 1,
            yAxisID: "bar"
          }
        },
        scales: {
          yAxes: [
            {
              id: "bar",
              type: 'category',
              stacked: true,
              labels: ['bar'],
              offset: true
            },
            {
              id: "line",
              position: 'right',
              ticks: {
                min: 0,
                stepSize: 1
              }
            }
          ]
        }
      }
    });
    

    Credit to the original author of this code (Jukka Kurkela aka kurkle). He answered this on the chart.js GitHub issues page.