Formatting time on the x-axis in a Chart.js graph

I've been attempting to create a scatter plot with Chart.js using some data, but no matter what I try from various internet resources, the x-axis continues to display as integers instead of dates. Here's a screenshot for reference.

UPDATE: I discovered that when I remove the square brackets around the axis properties, as suggested in the documentation, I encounter an error (

Uncaught Error: This method is not implemented: Check that a complete date adapter is provided.
). On the other hand, when I include the square brackets, the properties are not being recognized.

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="45262d2437316b2f3605766b716b74">[email protected]</a>/dist/chart.min.js"></script>
        <canvas id="mychart"></canvas>
    <script>
    
    data = [{
          x: new Date("2017-01-20"),
          y: 43
        }, {
          x: new Date("2017-01-21"),
          y: 45
        }, {
          x: new Date("2017-01-22"),
          y: 120
        }, {
          x: new Date("2017-01-23"),
          y: 100
        }]
    let options = {
      scales: {
        yAxes: [{ticks: {min: 0}}],
        xAxes: [{
            type: 'time',
            time: {
              unit: 'day',
              tooltipFormat: 'MMM DD'
            }
          }],
      },
    };
    
    let chartData = {
        //labels: labels,
      datasets: [{
        data: data,
        label: 'Amount of Stuff',
        backgroundColor: '#fffff',
      }]
    };
    
    let ctx = document.getElementById('mychart').getContext('2d');
    
    new Chart(ctx, {
        data: chartData,
      type: 'scatter',
      options: options,
    });
    </script>

The current output looks like this:

https://i.sstatic.net/Ijjpd.png

Answer №1

I finally identified the root cause of the issue:

The solution was to correctly reference an adapter temporarily and eliminate the square brackets surrounding the axis properties, as illustrated in the documentation:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>


<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3d0dbd2c1c7d9c09ed2d7d2c3c7d6c19ededcded6ddc7f3839d829d81">[email protected]</a>"></script>

<canvas id="mychart"></canvas>
    <script>
    
    data = [{
          x: new Date("2017-01-20"),
          y: 43
        }, {
          x: new Date("2017-01-21"),
          y: 45
        }, {
          x: new Date("2017-01-22"),
          y: 120
        }, {
          x: new Date("2017-01-23"),
          y: 100
        }]
    let options = {
      scales: {
        yAxes: {ticks: {min: 0}},
        xAxes: {
            type: 'time',
            time: {
              unit: 'day',
              tooltipFormat: 'MMM DD'
            }
          },
      },
    };
    
    let chartData = {
        //labels: labels,
      datasets: [{
        data: data,
        label: 'Amount of Stuff',
        backgroundColor: '#fffff',
      }]
    };
    
    let ctx = document.getElementById('mychart').getContext('2d');
    
    new Chart(ctx, {
        data: chartData,
      type: 'scatter',
      options: options,
    });
    </script>

Answer №2

If you want to customize how the data appears on the axis, implement a callback function.

let configuration = {
  scales: {
    yAxes: [{ticks: {min: 0}}],
    xAxes: [{
        type: 'time',
        time: {
          unit: 'day',
          tooltipFormat: 'MMM DD'
        },
        ticks: {
            callback: function(value, index, values){
                // modify the value here
                return value;
            }
        }
      }],
  },
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjusting an element within an array obtained from a computed property

Within my Vuex store, I retrieve an array of rooms from a Firebase/Firestore API call. This array structure is as follows: [{label:'Kitchen', description:'...'}, ...]. To make this array accessible to my application, I utilize a Vuex ge ...

Struggling to understand JSON in joint.js?

I am trying to utilize the joint.js library to render a JSON data as a chart... let paper = new joint.dia.Paper({ el: $('#paper'), width: 600, height: 200, model: graph }); let graph = new joint.dia.Graph; let json = '{"em ...

The division element nested within a select tag

HTML: <div class="row"> <div class="form-group"> <div class="col-xs-10"> <label for="class_code_reservation">Class Code</label> <select type="text" class="form-control" id="class_code_reservation" na ...

Can a website trigger an alarm on a user's iPhone without their permission?

Even though I have limited experience with HTML, CSS, and Javascript, I am curious if it is possible to create a basic website that can trigger an alarm on the user's device by simply clicking a button. For example, imagine a scenario where a user is ...

Discover the magic of TransformToggle and slideToggle in Javascript, HTML, and CSS

Working on a website coding project and ran into an issue. Trying to utilize an img as a link to slideToggle content. It's working, but I'd like the img to rotate 90deg on the first click and -90deg on the second one. Any solutions are greatly ap ...

Masking the identity of Google Pagespeed

Just starting to learn the ropes of javascript. How can I make Google Pagespeed anonymous? Check out the original code here: http://pastebin.com/xRbTekDA. It's functioning properly when I visit the page. Here is the anonymized version: http://pasteb ...

Tips for resolving the error "React import attempt":

I'm a beginner in learning React and I encountered this error when trying to export NavigationMenu and import it into Navigation: Failed to compile ./src/components/Navigation.js Attempted import error: 'NavigationMenu' is not exported from ...

Don't forget to set up your reminder notifications for Apple iOS devices with simple php

Here are the four notification settings available: 1. Renew Tax 2. Renew Health Insurance 3. Renew Car Insurance 4. Renew Residential Insurance If a user decides to turn off any of these settings on their mobile phone, NO notifications will be sent. How ...

Adding a data attribute to a group of elements derived from an array

Looking to enhance the functionality of a slick slider by creating a custom navigation with buttons that will work alongside the original navigation dots. To achieve this, I need to extract the 'data-slick-index' attribute from every fourth slid ...

AngularJS: How can components effectively communicate with each other using best practices?

I've been struggling to figure out how to facilitate communication between components. The primary question that has stumped me is: when should I opt for $watch versus $on ($broadcast/$emit) to establish component communication? I've identified ...

AngularJS UI.Router ActiveState implemented with a dropdown menu feature

I am currently working on creating a menu with dropdown functionality for multiple links within my application. My goal is to have the dropdown menu display as "active" when one of the links below is active. I have managed to make either the link in the ...

Show a specific form field based on the chosen option in a dropdown menu using Angular and TypeScript

I am looking to dynamically display a form field based on the selected value from a dropdown list. For instance, if 'first' is chosen in the dropdown list, I want the form to remain unchanged. However, if 'two' is selected in the drop ...

You cannot assign a promise to a React state

Calling a function from MoviesPage.tsx to fetch movie data results in a promise containing an object that is successfully fetched (can confirm by console logging). However, I'm facing an issue when trying to assign the result to a state - receiving a ...

Bootstrap 4 Nav Table of Contents with Expand and Collapse Feature

Currently, I am encountering an issue with implementing a button to expand and collapse a "table of contents" in Bootstrap 4. The code I have so far can be viewed here: https://codepen.io/nht910/pen/RwwwyKB Code Snippet: <div class="main-wrapper col- ...

Generate a string that will be utilized to interpret a JSON response

I can't seem to extract a specific element from a json using a dedicated function. Can someone please assist me with this issue? Here is the fiddle that I have created for reference: http://jsfiddle.net/jonigiuro/N5TTM/2/ CODE: var data = { "res ...

Error encountered while making a REST API call in Ajax: Unforeseen SyntaxError: Colon unexpected

I am currently troubleshooting my code to interact with a REST API. My platform of choice is "EspoCRM" and I aim to utilize its API functionalities. The official documentation recommends using Basic Authentication in this format: "Authorization: Basic " ...

Setting up a Vue 3 parent component to emit events to a child component: a step-by-step guide

Seeking assistance with setting up a Vue 3 Tailwind parent component button to trigger a HeadlessUI transition event in a child component. The objective is for the button in the parent to emit an event, which the child will then watch for before triggering ...

Experimenting with nested dual dynamic routing within the app's directory

Currently working with NextJS 13 and executing the following operations within the app directory. I am attempting to utilize the generateStaticParams function to generate static pages during build time. The route structure is: subpage/[categoryName]/[gif ...

When it comes to AFrame+Three.js, which is more efficient: having numerous meshes with minimal triangles per mesh or having a few meshes with a high number of

Currently working with Aframe 1.0.4 and Three.js 111, I am exploring the performance differences between: Whether it is better to have a few entities with a high number of triangles or many entities with fewer triangles each. Specifically, I am debating ...

What is the best way to trigger an API call every 10 seconds in Angular 11 based on the status response?

I am in need of a solution to continuously call the API every 10 seconds until a success status is achieved. Once the success status is reached, the API calls should pause for 10 seconds before resuming. Below is the code I am currently using to make the A ...