Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chartjs linechart with only one point - how to center

Tags:

chart.js

I have a chartjs linechart diagram to show the sales of different products on a range of dates. The user can select a date range (for example from 2015-12-01 to 2015-12-10) to view the sales per day and thats fine and its working.

But if the user selects only one day (range from for example 2015-12-01 to 2015-12-01), he gets the correct diagram, but it doesn't look good:

enter image description here

As you can see, the points are stick to the y-axis. Is there a possibility, to center the points on the diagram?

Thats how it should look like:

enter image description here

like image 334
bernhardh Avatar asked Dec 11 '15 14:12

bernhardh


2 Answers

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

like image 107
Manhar Sapra Avatar answered Oct 01 '22 14:10

Manhar Sapra


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/

like image 29
potatopeelings Avatar answered Oct 01 '22 16:10

potatopeelings