Marty
Marty

Reputation: 131

How to adjust axis width independently of gridLines lineWidth in chart.js graphs?

For my charts, I am trying to have thin gridlines and thicker axis lines (both x and y).

I found an option to adjust zeroLineWidth but this is only applicable for 0 and my axis does not start at 0 (E.g. x-axis are years, so starting at 0 makes no sense). I found some discussions about it but as far as I can tell this does not work yet: https://github.com/chartjs/Chart.js/pull/4117.

I also tried to supply an array for the gridLines lineWidth option. The first value changes the thickness of the axis but also of the first gridline. So this is not fully independent.

scales: {
    yAxes: [{
        gridLines: { 
            lineWidth: [5,1,1,1,1,1,1,1,1]
        }
    }]
}

Maybe there is no way to do this right now but if anyone has a solution that would be great. Even a hacky one would be welcome.

Upvotes: 1

Views: 7573

Answers (1)

timclutton
timclutton

Reputation: 13014

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>

Upvotes: 3

Related Questions