ruby-on-railschart.jschartkick

How to just show x-axis (at y = 0) using chartkick (chart.js)?


I want to just have the x-axis at y = 0 showing on my bar chart, i.e. the just the green line shown below.

enter image description here

What chart.js/chartkick configuration should I use to achieve this? Or do I have to directly plot it? If so, how do I achieve this?

At the moment, I have the following chart.js configuration, which has removed all lines including the desired x-axis.

library: {
    scales: {
        yAxes: [{
            ticks: {
                display: false,
            },
            gridLines: {
                display: false,
            }
        }],
        xAxes: [{
            ticks: {
                display: false,
            },
            gridLines: {
                display: false
            }
        }],
    },
}
                                
                            

Solution

  • Assuming you're using Chart.js version 2.9.4, this could be done by defining yAxis.gridLines as follows:

    gridLines: {
      lineWidth: 0,
      zeroLineWidth: 3,
      zeroLineColor: 'rgb(101, 157, 52)',
      z: 10
    }
    

    For further details about individual grid line options, please consult Chart.js v2.9 documentation.

    Please take a look at below runnable code and see how it works.

    new Chart('chart', {
      type: 'bar',
      data: {
        labels: ['A', 'B', 'C'],
        datasets: [{
          label: 'My Dataset',
          data: [50, -15, 30],
          backgroundColor: 'rgba(0, 0, 255, 0.2)',
          borderColor: 'rgb(0, 0, 255)',
          borderWidth: 2
        }]
      },
      options: {
        legend: {
          display: false
        },
        scales: {
          yAxes: [{
            ticks: {
              display: false
            },
            gridLines: {
              lineWidth: 0,
              zeroLineWidth: 3,
              zeroLineColor: 'rgb(101, 157, 52)',
              z: 10
            }
          }],
          xAxes: [{
            ticks: {
              display: false
            },
            gridLines: {
              display: false
            }
          }]
        }
      }
    });
    canvas {
      max-width: 400px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
    <canvas id="chart" height="120"></canvas>