score:9

Accepted answer

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/

score: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 :)

score: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

score:22

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


Related Query

More Query from same tag