[Chartjs]-Chart.js How to set line height only to the points?

3👍

It’s not a native option in Chart.js but you can implement it yourself via plugin. See the annotations in the below code.

new Chart(document.getElementById('chart'), {
  type: 'line',
  data: {
    labels: [0, 1, 2, 3, 4, 5],
    datasets: [{
      label: 'series 1',
      data: [0, 2, 4, 3, 1, 0]
    }]
  },
  options: {
    maintainAspectRatio: false,
    scales: {
      xAxes: [{
        gridLines: {
          display: false, // must be false since we're going to draw our own 'gridlines'!
          color: 'rgba(255, 0, 0, .2)', // can still set the colour.
          lineWidth: 5 // can still set the width.
        }
      }],
      yAxes: [{
        gridLines: {
          display: false
        },
        ticks: {
          beginAtZero: true
        }
      }]
    }
  },
  plugins: [{ // this is the magical bit :)
    afterRender: function(c, options) {
      let meta = c.getDatasetMeta(0),
        max;
      c.ctx.save();
      c.ctx.strokeStyle = c.config.options.scales.xAxes[0].gridLines.color;
      c.ctx.lineWidth = c.config.options.scales.xAxes[0].gridLines.lineWidth;
      c.ctx.beginPath();
      meta.data.forEach(function(e) {
        if (max == undefined || c.config.data.datasets[0].data[e._index] > max) {
          max = c.config.data.datasets[0].data[e._index];
        }
        c.ctx.moveTo(e._model.x, meta.dataset._scale.bottom);
        c.ctx.lineTo(e._model.x, e._model.y);
      });
      c.ctx.textBaseline = 'top';
      c.ctx.textAlign = 'right';
      c.ctx.fillStyle = 'black';
      c.ctx.fillText('Max value: ' + max, c.width - 10, 10);
      c.ctx.stroke();
      c.ctx.restore();
    }
  }]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<canvas id="chart"></canvas>

Leave a comment