[Chartjs]-Chartjs linechart with only one point โ€“ how to center

9๐Ÿ‘

โœ…

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/

28๐Ÿ‘

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

0๐Ÿ‘

Wanted to add to the above answer and say that I got a similar effect on a time series scatter plot using this:

if (values.length === 1) {
        const arrCopy = Object.assign({}, values);
        values.unshift({x: arrCopy[0].x - 86400000, y: null});
        values.push({x: arrCopy[0].x + 2 * 86400000, y: null});
}

That only handles for a single point, however. To add in functionality for multiple points, I did the following:

const whether = (array) => {
    const len = array.length;
    let isSame = false;
    for (let i = 1; i < len; i++) {
        if (array[0].x - array[i].x >= 43200000) {
            isSame = false;
            break;
        } else {
            isSame = true;
        }
    }
    return isSame;
}
if (values.length === 1 || whether(arr[0])) {
        const arrCopy = Object.assign({}, values);
        values.unshift({x: arrCopy[0].x - 86400000, y: null});
        values.push({x: arrCopy[0].x + 2 * 86400000, y: null});
}

You might notice Iโ€™m just subtracting/adding a day in milliseconds into the x values. To be honest, I was just having the worst of times with moment.js and gave up haha. Hope this helps someone else!

Note: my code has a tolerance of 43200000, or 12 hours, on the time. You could use moment.js to compare days if you have better luck with it than I did tonight ๐Ÿ™‚

0๐Ÿ‘

For your specific problem, try to modify the options->scales->xAxes option like so:

options: {
      title: {
         display: true,
         text: 'mytitle1'
      },
      scales: {
         xAxes: [{
            type: 'linear',
            ticks: {
               suggestedMin: 0,
               suggestedMax: (11.12*2),
               stepSize: 1 //interval between ticks
            }
         }],

More info at: Chart JS: Ignoring x values and putting point data on first available labels

Leave a comment