[Chartjs]-Chart.js – mixing bar and line graphs – can I get the lines to fill the full column?

13👍

Unfortunately, there isn’t a way to “configure” the chart to achieve what you want. It all has to do with how the line chart scale drawing works. With that said, you can still achieve this behavior by tricking chart.js using some “dummy” data.

Basically, you create a “dummy” first and last label. Then add a corresponding “dummy” first and last value to your bar data array (this data will never be displayed). Then add a corresponding “dummy” first and last value to your line data array, but make sure you set the value the same as the next/prev value to end up with a straight line (otherwise your line will angle at the beginning and end). Here is what I mean.

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['dummy1', 'Jan 21st', 'Feb 21st', 'Mar 21st', 'Apr 21st', 'dummy2'],
    datasets: [
      {
        type: 'bar',
        label: 'A',
        // the 1st and last value are placeholders and never get displayed on the chart
        data: [0, 10, 25, 18, 37, 0],
      },
      {
        type: 'line', 
        label: 'B',
        // the 1st and last value are placeholders and never get displayed on the chart
        // to get a straight line, the 1st and last values must match the same value as
        // the next/prev respectively
        data: [25, 25, 25, 25, 25, 25],
        fill: false,
        borderWidth: 1,
        borderColor: '#f00',
        borderDash: [5,4],
        lineTension: 0,
        steppedLine: true
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],  
      xAxes: [{
        // exclude the 1st and last label placeholders by specifying the min/mix ticks
        ticks: {
          min: 'Jan 21st',
          max: 'Apr 21st',
        }
      }],
    }
  }
});

Checkout this codepen example to see it in action.

Leave a comment