Chartjs linechart with only one point - how to center

You can check the length of your labels (or data) arrays and add dummy non-renderable points to the left and right by using empty string labels and null value, like so

var chartData = {
  labels: ['', "A", ''],
  datasets: [
    {
      fillColor: "rgba(255, 52, 21, 0.2)",
      pointColor: "#da3e2f",
      strokeColor: "#da3e2f",
      data: [null, 20, null]
    },
    {
      fillColor: "rgba(52, 21, 255, 0.2)",
      strokeColor: "#1C57A8",
      pointColor: "#1C57A8",
      data: [null, 30, null]
    },
  ]
}

Fiddle - https://jsfiddle.net/pf24vg16/


Instead of hardcoding the labels and values with blank parameters, use the offset property.

const options = {
  scales: {
    x: {
      offset: true
    }
  }
}

Documentation: https://www.chartjs.org/docs/latest/axes/cartesian/linear.html#common-options-to-all-cartesian-axes

Tags:

Chart.Js