Chartjs-How to add a vertical line on the end of the chart.js scatter graph

1👍

This can be solved as follows:

Define data.labels in the chart configuration. Given your data, this could be done by extracting the x values of of the data objects using Array.map().

const labels = data.map(o => o.x);

Then you need to adapt xAxis.ticks in order to instruct Chart.js that ticks (including grid lines) have to be generated from user given labels (see Tick Source from Chart.js documentation).

ticks: {
  source: 'labels'            
}

Further you have to change the definition of xAxis.gridLines. Make them displayed again and define lineWidth instead. This should be an array of numbers that specify the stroke width of individual grid lines. Basically all 0 except 1 for the last number.

gridLines: {
  lineWidth: labels.map((l, i) => i < labels.length - 1 ? 0 : 1)
}

Please have a look at the runnable code snippet below.

const data = [
  { x: "1-01", y: 1 },
  { x: "1-07", y: 3 },
  { x: "1-14", y: 2 },
  { x: "1-21", y: 4 },
  { x: "1-28", y: 5 },
  { x: "2-04", y: 1 }
];
const labels = data.map(o => o.x);

new Chart('line-chart', {
  type: "scatter",
  responsive: true,
  maintainAspectRatio: false,
  data: {
    labels: labels,
    datasets: [
      {
        data: data,
        label: "A",
        showLine: true,
        fill: false,
        borderWidth: 4,
        pointRadius: 5,
        tension: 0,
        backgroundColor: "#ffffff",
        borderColor: "red"
      }
    ]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      xAxes: [
        {
          type: 'time',
          unit: 'day',
          time: {
            parser: 'M-D'
          },
          gridLines: {
            lineWidth: labels.map((l, i) => i < labels.length - 1 ? 0 : 1)
          },
          ticks: {
            source: 'labels',
            padding: 15            
          }
        }
      ],
      yAxes: [
        {
          ticks: {
            padding: 22,
            min: 1,
            max: 5,
            stepSize: 1
          },
          position: "left",
          gridLines: {
            drawTicks: false
          }
        }
      ]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="line-chart" height="90"></canvas>

Leave a comment