[Chartjs]-How to adjust axis width independently of gridLines lineWidth in chart.js graphs?

3👍

It looks like there’s no way to do this since (as you noticed) the axis line width is directly derived from the gridline width via this line in the Chart.js source:

var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;

But, since you say a hacky solution is welcome…

The below snippet demonstrates combining two axes to achieve the desired affect; one for the border and one for the gridlines.

It’s ugly, but functional.

let border_axis = {
    gridLines: {
      drawOnChartArea: false,
      lineWidth: 10,
      color: "rgba(255, 127, 0, 0.25)"
    },
    ticks: {
      beginAtZero: true
    }
  },
  gridline_axis = {
    beforeBuildTicks: function(axis) {
      if (axis.id == "y-axis-1") {
        // this callback ensures both axes have the same min/max to keep ticks and gridlines aligned.
        axis.max = axis.chart.scales["y-axis-0"].max;
        axis.min = axis.chart.scales["y-axis-0"].min;
      }
    },
    gridLines: {
      drawTicks: false,
      drawBorder: false
    },
    ticks: {
      display: false
    }
  },
  chart = new Chart(document.getElementById("chart"), {
    type: "line",
    data: {
      labels: [2001, 2002, 2003, 2004, 2005],
      datasets: [{
        data: [1, 2, 3, 4, 5]
      }]
    },
    options: {
      scales: {
        xAxes: [border_axis, gridline_axis],
        yAxes: [border_axis, gridline_axis]
      }
    }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<canvas id="chart"></canvas>

Leave a comment