[Chartjs]-Border behind grid line

2๐Ÿ‘

โœ…

You can draw your own grid lines directly on to the canvas using the Plugin Core API. It offers different hooks that may be used for executing custom code. You can use the afterDraw hook to draw vertical lines up to individual points contained in the dataset but stop just underneath the line.

ctx.lineTo(x, yTop + 2);

Please have a look at your amended code below.

new Chart('myChart', {
  type: "line",
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;      
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      ctx.save();
      xAxis.ticks.forEach((value, index) => {
        var x = xAxis.getPixelForTick(index);
        var yTop = yAxis.getPixelForValue(chart.config.data.datasets[0].data[index]);        
        ctx.strokeStyle = '#f8f8f8';
        ctx.lineWidth = 2;
        ctx.beginPath();
        ctx.moveTo(x, yAxis.bottom);
        ctx.lineTo(x, yTop + 2);
        ctx.stroke();        
      });
      ctx.restore();
    }
  }],
  data: {
    labels: [2.7, 3.7, 5.7, 6.7, 7.7, 8.8, 9.9],
    datasets: [{
      data: [86, 114, 106, 106, 107, 111, 133],
      borderColor: "#3e95cd",
      backgroundColor: "rgba(63, 121, 230, 0.4)",
      fill: true
    }]
  },
  options: {
    legend: {
      display: false
    },
    elements: {
      point: {
        radius: 0
      }
    },
    scales: {
      xAxes: [{
        gridLines: {
          display: false,
        }
      }],
      yAxes: [{
        gridLines: {
          drawBorder: false,
          display: false
        },
        ticks: {
          display: false,
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="100"></canvas>

2๐Ÿ‘

Use borderWidth: 0 inside the datasets as the following.

...
datasets: [
  {
    data: [86, 114, 106, 106, 107, 111, 133],
    borderWidth: 0,
    backgroundColor: "rgba(63, 121, 230, 0.4)",
    fill: true,
  },
],
...

Leave a comment