End x-axis on last data point (scatter plot) for x,y numeric values

Viewed 437

When I plot a dataset of (x,y) floats on a scatter plot using ChartJS, I end up with extra space on my x-axis due to the step size. Can I force it to end right on the last data point?

ElevationProfile

I have not set any nice labels or a legend, so sorry for the basic plot. I first tried to do a line plot, which I think would not have this problem, but I was not able to pass a dataset of (x,y) values in the format:

elevation = [
    {
        x: 1,
        y: 2
    },
    {
        x: 2,
        y: 5
    }
]

For this reason, I chose to use a scatter plot.

Currently I'm rendering my scatter chart like this:

var ctx = document.getElementById("elevationProfile");
myLineChart = new Chart(ctx, {
    type: 'scatter',
    data: {
        datasets: [{
            label: "Elevation Profile",
            data: elevation,
            showLine: true
        }]
    }
});

But I was unable to find anything in the docs or Github that would indicate how to achieve this.

I would like the graph to look like this with no space at the end:

ImprovedElevationProfile

Thanks!

1 Answers

I solved this on a similar project using xAxe.ticks.min / max attributes.

In your case, something like this should do the trick:

if (elevation[0]){
    var minX = elevation[0]['x'];
    var maxX = elevation[elevation.length -1]['x'];
}

myLineChart = new Chart(ctx, {
  type: 'scatter',
  data: {
      datasets: [{
          label: "Elevation Profile",
          data: elevation,
          showLine: true
      }]
  },
  options: {
    ...
    scales: {
      xAxes: [{
        ticks:{
          min: minX,
          max: maxX,
        }
      }]
    },
    ...
  }
});
Related