Search code examples
javascripttimechart.jsx-axis

Chart js - Chart doesn't show when x axis has type 'time'


I'm working on Char.js version 3.9.1 and I have a chart which display data (y value) along the time (x value). Everything seems to be working fine.

However, when I add 'type' property to x axis in order to make the x scale to have daily unit, the chart doesn't show anything. I have tried running code in jsfiddle and the console shows error "Uncaught Error: This method is not implemented: Check that a complete date adapter is provided." I tried searching the internet and still not find any solution.

Here is my code (I have to add comment over type: 'line' to make the chart to display).

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js" integrity="sha512-ElRFoEQdI5Ht6kZvyzXhYG9NqjtkmlkfYk0wr6wHxU9JEHakS7UJZNeml5ALk+8IKlU6jDgMabC3vkumRokgJA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<canvas id="mychart"></canvas>

Javascript

let data = [12, 14, 13, 18, 21, 22, 25];
let labels = ["2017-01-20", "2017-01-22", "2017-01-24", "2017-01-26", "2017-01-28", "2017-01-30", "2017-02-01"];

let options = {
  scales: {
    x: {
      type: 'time', //this line make the chart disappear
      time: {
        unit: 'day'
      }
    },
    y0: {
      ticks: {
        min: 0
      }
    },
  },
};

let chartData = {
    labels: labels,
    datasets: [{
      data: data,
      label: 'Amount of Stuff',
      backgroundColor: '#035e7b',
    }]
};

let ctx = document.getElementById('mychart').getContext('2d');

new Chart(ctx, {
  data: chartData,
  type: 'line',
  options: options,
});

Solution

  • From the docs:

    Date Adapters
    The time scale requires both a date library and a corresponding adapter to be present. Please choose from the available adapters.

    So you can change your HTML like this:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js" integrity="sha512-ElRFoEQdI5Ht6kZvyzXhYG9NqjtkmlkfYk0wr6wHxU9JEHakS7UJZNeml5ALk+8IKlU6jDgMabC3vkumRokgJA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdn.jsdelivr.net/npm/moment@^2"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>
    
    
    <canvas id="mychart"></canvas>
    

    and then you'll be able to use type: "time" for x axis. time for x axis