Chart.js: Display only the horizontal gridline at zero index
Asked Answered
N

4

5

How can I display the horizontal gridline present with zero value?

I am currently using the following code:

yAxes: [{
    gridLines: {
        display: true,
        color: [
            "rgba(0, 0, 0, 0.1)",
            "rgb(255, 255, 255)",
            "rgb(255, 255, 255)",
            "rgb(255, 255, 255)",
            "rgb(255, 255, 255)"
        ],
    },
    afterTickToLabelConversion: function (scaleInstance) {
        scaleInstance.ticks.unshift(null);
        scaleInstance.ticksAsNumbers.unshift(null);
        scaleInstance.zeroLineIndex++
        display: false
    },

This works fine when the charts are being displayed on the HTML page with a white background.

However, when the chart is saved and seen in a picture viewer, the white line comes up (I need to hide / remove these line while keeping the line at the zero position).

Example:

Example

Nipa answered 19/7, 2017 at 9:44 Comment(0)
E
11

These settings worked for me:

gridLines: {
  color: "transparent",
  display: true,
  drawBorder: false,
  zeroLineColor: "#ccc",
  zeroLineWidth: 1
}

http://www.chartjs.org/docs/latest/axes/styling.html#grid-line-configuration

Elysia answered 22/11, 2017 at 20:52 Comment(0)
I
5

This also seems to work:

gridLines: {
  lineWidth: 0,
  zeroLineWidth: 1
}
Irony answered 9/6, 2020 at 5:57 Comment(0)
S
4

The other answers weren't working for me, I believe because how you do this has changed with Chart.js 3.x

To achieve the chart in the question in 3.x, you need the below options object.

  const options = {
    scales: {
      x: {
        grid: {
          lineWidth: 0,
          drawBorder: false,
        }
      },
      y: {
        grid: {
          lineWidth: context => context.tick.value == 0 ? 1 : 0 //Set only 0 line visible

        }
      }
    }

More info that helped me solve this Chart.js how to use scriptable options

Schroeder answered 16/7, 2022 at 8:30 Comment(1)
not working for me, also typescript is giving an error with contextFoxhole
A
0

Great solution from Ted Whitehead. I found this also works with simply;

gridLines: {
  color: "transparent"
}
Allotment answered 4/3, 2021 at 1:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.