How to draw a line in line chart for single value in Charts.JS

0👍

There exists different approaches to solve this problem.

  1. According to the answer I gave to a similar question, you can define an animation.onComplete function to draw the line.

  2. In a comment on before mentioned answer, Lakshmansundeep suggested an approach where he defines the same data value three times but makes sure, pointRadius for the leading and ending data point is zero.

datasets: [{
  data: [120, 120, 120],
  ...
  pointRadius: [0, 4, 0],
  pointHoverRadius: [0, 4, 0],
}],

For the second approach, please have a look at the code below.

new Chart('line-chart', {
  type: "line",
  data: {
    labels: [null, 'A', null],
    datasets: [{
      data: [120, 120, 120],
      fill: false,
      backgroundColor: "#0168FF",
      borderColor: "#0168FF",
      pointBackgroundColor: "white",
      pointBorderWidth: 1,      
      lineTension: 0,
      pointBorderColor: "blue",
      pointRadius: [0, 4, 0],
      pointHoverRadius: [0, 4, 0],
    }],
  },
  options: {
    legend: {
      display: false
    },
    tooltips: {
      enabled: false
    },
    scales: {
      yAxes: [{
        ticks: {
          padding: 20,
          min: 0,
          stepSize: 100
        },
        gridLines: {
          drawBorder: false
        }
      }],
      xAxes: [{
        ticks: {
          display: false
        },
        gridLines: {
          zeroLineColor: "transparent",
          drawBorder: false,
          display: false
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="line-chart" height="80"></canvas>

Leave a comment