Search code examples
chart.jschartjs-2.6.0

chartjs plot datetime value with time offset on the grid


I have a ChartJS line chart displaying Datetime values.

Each value is displayed on the chart exactly in the vertical line where the XAxis day label is located.

What I need is to plot the data based on the time for that day. So for example, if I have two data points:

{ t: '2019-08-15T09:00:00Z', y: 0.3 },
{ t: '2019-08-15T17:00:00Z', y: 0.3 }

What I should see is that first data point will be show a little bit offset from the day grid vertical line while the second data point will be ploted to the right of the first point.

Something similar as the next image:

enter image description here

Is this possible?


Solution

  • That should be the default behaviour for the time axis, assuming it's configured correctly. I've added a couple of data points to your set so as to illustrate in the snippet below.

    Also, I see that you've tagged your question as chartjs-2.6.0. Axis handling was significantly improved in more recent releases so upgrade if you can.

    new Chart(document.getElementById("chart"), {
      type: "line",
      data: {
        datasets: [{
          data: [{
              t: '2019-08-14T09:00:00Z',
              y: 0.1
            },
            {
              t: '2019-08-15T09:00:00Z',
              y: 0.3
            },
            {
              t: '2019-08-15T17:00:00Z',
              y: 0.3
            },
            {
              t: '2019-08-16T09:00:00Z',
              y: 0.5
            }
          ]
        }]
      },
      options: {
        scales: {
          xAxes: [{
            type: "time",
            time: {
              unit: "day"
            }
          }]
        }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
    <canvas id="chart"></canvas>