How to only show zero grid axes at center and hide all other gridlines in chart js

0👍

You can use scriptable options for the grid color to achieve this:

Chart.register(ChartDataLabels);

chartLabels = ['2018', '2019', '2020', 'TTM']
equityToAssetData = [4.32, -5.37, 4.73, 4.89, 3.6, ];

var equityToAssetDatasets = {
  labels: chartLabels,
  datasets: [{
    type: 'line',
    label: 'Equity to Asset ',
    data: equityToAssetData,
    backgroundColor: 'rgb(97,207,5)',
    borderColor: 'rgb(97,207,5)',
    borderWidth: 1.8,
    lineTension: 0.4,
    pointStyle: 'rectRot'
  }]
}

var chartStylingSingle = {
  animation: {
    duration: 500,
  },
  responsive: true,
  layout: {
    padding: 20
  },
  interaction: {
    mode: 'index',
    intersect: false
  },
  elements: {
    point: {
      hoverRadius: 5
    }
  },
  plugins: {
    legend: {
      display: false,

    },
    datalabels: {
      borderWidth: 0.5,
      color: 'green',
      anchor: 'start',
      align: 'end',
      offset: 6,
      formatter: (v, ctx) => {
        let label = ctx.chart.data.labels[ctx.dataIndex];
        if (label != 'TTM') {
          label = ' ' + label;
        }
        return label + '\n ' + v;
      },
      font: {
        size: 11,
        weight: 'bold',

      }

    }
  },
  scales: {
    y: {
      display: true,
      grid: {
        color: (ctx) => (ctx.tick.value === 0 ? 'rgba(0, 0, 0, 0.1)' : 'transparent')
      }
    },
    x: {
      display: true,
      grid: {
        display: false,
      }
    }
  }
}




var ctx = document.getElementById('equityToAsset').getContext('2d');

var myChart = new Chart(ctx, {
  data: equityToAssetDatasets,
  options: chartStylingSingle
})
<canvas id="equityToAsset"></canvas>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></script>

Leave a comment