Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plot a bar chart.js time series

I am trying to plot a bar chart with multiple datasets on a time series, however some of the data gets lost along the way.

for simplicity I have removed the ajax call and plotted some data:-

 var config = {
    type: 'bar',
    data: {
      datasets: [{
            label: "Dataset 1",
            data: [{
                x: new Date('2017-03-01'),
                y: 1
            }, {
                x: new Date('2017-03-02'),
                y: 2
            }, {
                x: new Date('2017-03-03'),
                y: 3
            }, {
                x: new Date('2017-03-04'),
                y: 4
            }],
            backgroundColor: "red"
        }, {
            label: "Dataset 2",
            data: [{
                x: new Date('2017-03-01'),
                y: 1
            }, {
                x: new Date('2017-03-02'),
                y: 2
            }, {
                x: new Date('2017-03-03'),
                y: 3
            }, {
                x: new Date('2017-03-04'),
                y: 4
            }],
            backgroundColor: "blue"
        }]
    },
    options: {
      scales: {
        xAxes: [{
          type: "time",
          time: {
            unit: 'day',
            round: 'day',
            displayFormats: {
              day: 'MMM D'
            }
          }
        }],
        yAxes: [{
          ticks: {
            beginAtZero: true
          }
        }]
      }
    }
  }

  var ctx = document.getElementById("canvas").getContext("2d");
  window.myLine = new Chart(ctx, config);

using the above configuration dataset 1 point 1 and dataset 2 point 4 (so basically the first and last points) do not get drawn.

Any ideas where I am going wrong here?

Also I am using this time series version because I was hoping to have "gaps" in the chart, for example dataset 1 might have a series for 2017-03-01 and dataset 2 might not, in this case dataset 2's next date will bunch up to dataset 1's making it look like it does belong to that date.

Any help would be appreciated

like image 628
Chris Avatar asked Apr 17 '18 08:04

Chris


1 Answers

I had the exact same issue when displaying a bar chart with time as the X axes.

Inside your xAxes you need to add an additional configuration option:

xAxes: [{
    offset: true
}]

Description from the ChartJS documentation:

If true, extra space is added to the both edges and the axis is scaled to fit into the chart area. This is set to true in the bar chart by default.

ChartJS Documentation Cartesian

like image 185
JonHayman Avatar answered Sep 28 '22 07:09

JonHayman