Creating a time-based scatter plot using chart.js

As I attempt to visualize a scatter plot using chart.js with (x,y) data where x represents a date string, I have noticed that most tutorials and examples available online utilize a function to generate a timestamp for demonstration purposes. However, I am yet to come across examples that demonstrate the use of actual collected data.

The dataset I possess is as follows (obtained from cron):

2017-07-08T06:15:02-0600,23.375
2017-07-08T06:20:02-0600,23.312
2017-07-08T06:25:02-0600,23.312
2017-07-08T06:30:02-0600,23.25

When attempting to input this data into chart.js (both with and without placing quotes around the data string), I used the following format:

data: [{
  x: 2017-07-08T06:15:02-0600,
  y: 23.375
},{
  x: 2017-07-08T06:20:02-0600,
  y: 23.312
},{
  x: 2017-07-08T06:25:02-0600,
  y: 23.312
},{
  x: 2017-07-08T06:30:02-0600,
  y: 23.25
}],

Unfortunately, nothing seems to render. Can anyone point out what mistake I might be making?

Answer №1

As stated in the scatter chart documentation:

While a line chart accepts data in different formats, scatter charts only accept point format data.

This means that date values like 2017-07-08T06:15:02-0600 cannot be used directly. Instead, dates need to be converted into numbers for use in the data.

In the scenario provided:

data: [{
        x: 1499516102000,
        y: 23.375
    }, {
        x: 1499516402000,
        y: 23.312
    }, {
        x: 1499516702000,
        y: 23.312
    }, {
        x: 1499517002000,
        y: 23.25
    }
]

By converting dates to numbers for the xAxes, it becomes possible to utilize a callback function to adjust xAxes labels accordingly.

Answer №2

That tip is a game-changer. By using the Javascript library moment.js, I was able to successfully plot scatter data with dates on the x-axis. Surprisingly, the built-in version in Chart.bundle.js wasn't functioning for me, so I opted to directly download moment.js. Here's how I set it up:

<script src="js/moment.js"></script>
<script src="js/Chart.min.js"></script>

For my chart.js data specifics, I used the following code:

data: [
  {x: moment("2017-07-08T06:15:02-0600"), y: 23.375},
  {x: moment("2017-07-08T06:20:02-0600"),y: 23.312},
  {x: moment("2017-07-08T06:25:02-0600"),y: 23.312},
  {x: moment("2017-07-08T06:30:02-0600"),y: 23.25}
],

The results are beyond satisfactory!

Answer №3

One clever approach that proved effective for me was utilizing the line type for the chart. By configuring it to use dates on the x-axis and disabling lines, we can achieve a scatterplot-like appearance.

new Chart(ctx, {
        type: 'line',
        data: {
            datasets: [{
                x: 2017-07-08T06:15:02-0600,
                y: 23.375
              },{
                x: 2017-07-08T06:20:02-0600,
                y: 23.312
              },{
                x: 2017-07-08T06:25:02-0600,
                y: 23.312
              },{
                x: 2017-07-08T06:30:02-0600,
                y: 23.25
            }]
          },
          options: {
            showLine: false,
            scales: {
              x:{
                type: 'time',
                display: true,
                title: {
                  display: true,
                  text: 'Date'
                },
              },
            }
          }
       }
    );

This solution strikes me as particularly elegant. The documentation further clarifies:

The scatter chart supports all of the same properties as the line chart. By default, the scatter chart will override the showLine property of the line chart to false.

Answer №4

After searching through various solutions, I decided to create my own working example.

new Chart(document.getElementById("chart"), {
    type: "line",
    data: {
      datasets: [
        {
          showLine: false,
          fill: false,
          data: [
            {
              x: new Date(Date.now()),
              y: 100,
            },
            {
              x: new Date(Date.now() + 1000 * 60 * 60),
              y: 200,
            },
            {
              x: new Date(Date.now() + 2000 * 60 * 60),
              y: 300,
            },
            {
              x: new Date(Date.now() + 3000 * 60 * 60),
              y: 400,
            },
          ],
        },
      ],
    },
    options: {
      plugins: {
        legend: {
          display: false,
        },
        title: {
          text: "Chart.js Time Scale",
          display: true,
        },
      },
      scales: {
        x: {
          type: "time",
          time: {
            unit: "hour",
            // Luxon format string
            // tooltipFormat: "DD T",
          },
          title: {
            display: true,
            text: "Hour",
          },
        },
        y: {
          title: {
            display: true,
            text: "value",
          },
        },
      },
    },
 });

The inspiration for this code came from: https://www.chartjs.org/docs/latest/samples/scales/time-line.html

To make it work, you will need to install momentjs and its adapter:

npm install moment chartjs-adapter-moment --save

Then import all libraries like this:

import Chart from "chart.js/auto";
import "chartjs-adapter-moment";

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

Utilizing the ajaxForm plugin within a view that is generated as an AJAX response

As I develop a messaging system for my website, I have implemented a flat mailbox design. This means that accessing the inbox or composing a new message does not navigate to a different page; instead, it toggles between div elements. When a user clicks on ...

Interactive image rotator featuring navigation buttons for next and previous slides

I recently followed a tutorial from W3Schools Now, I am looking to enhance it by adding previous / next buttons for the indicators, rather than for the slider itself Here is what I aim to accomplish: https://i.sstatic.net/qH1PQ.png Below is the code sn ...

Using JQuery to hide elements by setting CSS display as none instead of block

Is there a way to change the display of a content div to block when a specific tab is selected by the user, while hiding all other content divs? Here is the JQuery code I have tried so far: $(document).ready(function() { function resetTabs() { $("# ...

Grin schedule module JSON stream

I have integrated a Smile timeline widget on my website and successfully customized it following several tutorials. However, I am struggling to utilize a Json service instead of relying on data stored in a global variable within a JavaScript file. Despite ...

Tips for retrieving data from an Excel spreadsheet on an HTML/CSS webpage

I have a single HTML template at this location: . The current page is tailored for the state of Arkansas in the US, but I now need to replicate the design for all 50 states. Each state page will have the same layout, but different content specific to that ...

Unable to incorporate module into React project

Exploring React for the first time and attempting to import an npm module from the internet. Utilized npm install --save flag-icon-css for installation, which seems successful as there is now a folder for the module in the node_modules directory. However, ...

Unlocking the power of accessing nested data in JSON files dynamically

Building a new feature that allows users to input a word, choose the language, and receive the definition along with an example using the API service. To retrieve the desired data at position 0 of "exclamation" in the "meaning" section. This ensures that ...

Tips for ensuring the safety of your AJAX requests when using PHP and jQuery

Identifying the Challenge Lately, I have been exploring various AJAX methods to send data to a server for processing and storage in a MySQL database. The backend script that handles the AJAX request, api.php, is equipped with PHP's PDO prepared state ...

What is the name of the JavaScript code editor that includes line numbering for plain text?

Looking to incorporate a text area with line numbering features. I experimented with EditArea, but encountered difficulties when working with text files. While syntax highlighting for various programming languages would be a nice touch, my primary focus ...

Creating a responsive HTML5 webpage that adjusts seamlessly to all screen sizes without the need for scrolling

I have developed an HTML5 application for mobile devices. Currently, I have managed to address width-height issues by using a simple scroll feature when necessary. However, I have encountered a challenge with a particular page that contains a lot of conten ...

Cross domain widget ajax request

Our company offers a widget for clients to add to their websites. This widget requires a call to our website to validate user-entered data. However, due to domain restrictions, making ajax calls from the client's website to ours is not permitted. Is ...

Steps for transforming an array of file names into JSON format and including a specific key

I am in the process of creating a new website that will display all the files contained in a specific folder. However, I am facing an issue with converting an array of document names into JSON format. In order to achieve this, I understand that I need to ...

Interactive Card Matching Game featuring jQuery with a mix of images, numbers, and names

I recently added images to this Jquery Game, but now I'm facing a challenge. I want to match the numbers with their corresponding flower names (terms), for example, 1=Foglove. However, when I try to add terms in the code below, it randomizes both the ...

Contrast between the act of passing arguments and using apply with arguments

I have an important backbone collection that utilizes a save mixin to perform Bulk save operations (as Backbone does not natively support this feature). // Example usage of Cars collection define([ 'Car', 'BulkSave' ], function(Car ...

Troubleshooting the Gutter Problem in jQuery Isotope and Masonry

Currently, I am utilizing the Isotope jQuery plugin. While it is a fantastic tool, I am encountering a minor issue with aligning items in masonry mode. The width of my container is 960px, and I aim to have 4 items perfectly aligned as if they were adhering ...

Unleashing the power of XPath and wildcards in AJAX

Can anyone explain why the variable objProperties, which contains an xpath with a wildcard, is coming up empty in this scenario? function getXMLServerObject (httpType, cmd, isAsync) { var object = new Array(); $.ajax({ type: httpType, ...

Can data be transferred using ajax upon clicking a button and then utilizing the data in a form on the same page?

Is there a way to send data through ajax when a button is clicked and then use that value in a form on the same page? I have multiple buttons, each with a unique data attribute. I want the value of the clicked button to be sent via ajax and used within a ...

Why does the event handler capture multiple clicks when $.click() is triggered more than once for the same link?

My code looks like this: function init(){ $('.btn').click(function(){ //do something; } } Whenever new content is loaded via ajax, I make a call to init() to ensure the click event applies to the new buttons. However, each time I click ...

vue.js and the various elements that make up its architecture

My component content is not appearing!!! I have checked the router multiple times and it seems to be functioning correctly, but when I run the project, the components are empty. Even though I have added a lot of content to them, they appear to be blank. ...

Managing control among various child popups

In the situation I am facing, a parent window with login fields is present. In order to manage its controls, I have stored the window handle using: String parentWindow = idriver.getWindowHandle(); After entering the login credentials, a new popup (let&ap ...