Update the scatter/line chart dynamically in Chart.JS by incorporating multiple x and y grids for enhanced visualization

I need to develop a new function that will allow me to input data to update my line chart. Here is the current state of my function:

function updateChart(label, xp1, yp1, xp2, yp2) {
  chart.data.labels.push(label);
  chart.data.datasets.data.push({x: xp1, y: yp1}, {x: xp2, y: yp2}); 
  chart.update();
}

label is always a string

xp1, xp2, yp1, yp2 are decimal values

When I try to run the function in a loop, it doesn't update the chart and remains blank.

I referred to the Chart.js documentation but couldn't find a solution to my problem, and noticed some errors in their sample code.

This is the initial code for my chart:

var ctx = document.getElementById('chart').getContext('2d');
var chart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: [''],
        datasets: [{}]
    },
    options: {}
});

Here is the expected code after adding data:

var ctx = document.getElementById('chart').getContext('2d');
var chart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['a', 'b', 'c'],
        datasets: [{
            label: 'a',
            fill: false,
            data: [
                {
                    x: 0,
                    y: 9
                }, {
                    x: 3,
                    y: 9
                }
            ]
        },
        {
            label: 'a',
            fill: false,
            data: [
                {
                    x: 3,
                    y: 7
                }, {
                    x: 5,
                    y: 7
                }
            ]
        },
        {
            label: 'c',
            fill: false,
            data: [
                {
                    x: 5,
                    y: 5
                }, {
                    x: 10,
                    y: 5
                }
            ]
        }]
    },
    options: {}
});

Answer №1

To enhance your function, make the following adjustments:

function insertInfo(title, x1, y1, x2, y2) {
    graph.data.labels.push(title);
    graph.data.datasets.push([{ label: title, fill: false, data: [ {x: x1, y: y1}, {x: x2, y: y2} ] }]);
    graph.update();
};

Answer №2

If you need to modify your data and keep the color scheme consistent, you can simply use:

chart.data.datasets[0].data.push(   {x:5, y:2} ,{x:10, y:12},...,{x:50, y:25}      );

This approach makes it convenient to update your data series without disrupting the visual aesthetics.

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

The process of showcasing angularjs ng-repeat with a JSON object

I'm attempting to search for product results using AngularJS. I have retrieved a JSON object with my results, an example of which is shown below: [{"store_id":"17","user_id":"29","company_name":"Liquor R Us","company_type":"Alcohol", "phone":"(303) 5 ...

The jQuery closest selector seems to be malfunctioning when trying to scroll and focus on a specific class

My HTML code snippet is as follows: <div class="main"> <div class="sub-1"> <select> <option>1</option> <option>2</option> </select> </div> <div class="sub-2"> ...

How can you determine which of three intersecting three-dimensional objects should be displayed?

Let's imagine a scenario where multiple objects intersect at the same location. How can we specify which one to display in order to avoid constant flickering? http://jsfiddle.net/GYQ5v/187/ var scale = 1; var scene = new THREE.Scene(); var camera ...

Creating an expo apk using eas buildWould you like a tool for generating

Following an update to Expo, the process of building apk files using expo build:android -t apk is no longer supported. Instead, it now recommends using eas builds with the command eas build -p android --profile preview. However, this resulted in building a ...

Leveraging $last in Angular for obtaining the final visible element with ng-show

My ng-repeat container div contains multiple images, each with a corresponding div next to it. Using $last, I can make sure only the div of the final image is visible after all images. However, I also have a filter button on the page that hides certain im ...

The integration of ngx-translate with an HTTP interceptor is currently experiencing difficulties

Using ngxtranslate for application translation has been seamless so far. However, I am facing an issue with the HttpInterceptor. This interceptor attempts to retrieve data from local storage at the start and displays a dialog prompting you to either load t ...

Save the output of my Java function into a JavaScript variable

I have created a web application using JSP, CSS and HTML. The page contains six buttons, each of which calls a JavaScript method. For instance, the first button triggers the par() method. <html> <head> <title>Welcome d To Student Unive ...

What could be the reason that a MUI component does not disappear when the display is set to none in the sx prop?

I'm attempting to construct a responsive side drawer using MUI's Drawer component in React, specifically leveraging MUI version 4.12.1. In the example provided on the mui.com website, they utilize the sx prop and pass an object with different di ...

The socket.io client in my JavaScript code is failing to receive the necessary event

Currently, I am in the process of configuring a socket.io chat feature with an expressjs backend and sveltejs frontend. I have established a custom namespace named 'chat' where a new room is generated upon a 'join' request. My appro ...

Error Message: "Issue with jQuery mobile: Uncaught TypeError - Unable to read property 'abort' of undefined during AJAX request"

Hey there, I recently created a website using jQuery Mobile and implemented the autocomplete feature. However, I encountered an error message saying Cannot read property 'abort' of undefined. Here is the code snippet: <div id="myPage"> ...

Utilizing RXJS in Angular to pull information from numerous services within a single component

There are two services, ser1 and ser2. getdata1() { this.http.get<{message:string,Data1:any}>('http://localhost:3000/api/1') .pipe(map((data1)=>{ return Data1.Data1.map(data=>{ return { id: d ...

Dominant Editing through ASP.Net Roles

Looking for guidance on how to effectively use knockout with asp.net membership roles in MVC 4. My goal is to incorporate an editable grid on the page based on whether the user is an administrator or a 'registered user'. I want to ensure that use ...

How to fetch an image from a web API using JavaScript

I have recently entered the world of web development and I am facing an issue where I am trying to retrieve a Bitmap Value from a web api in order to display it on an HTML page using JavaScript. However, despite my efforts, the image is not getting display ...

Issue encountered while attempting to load external JSON file from server in AngularJS

Currently, I am attempting to load a JSON file from the server. Below is my services.js file: angular.module('starter.services', []) /** * A simple example service that returns some data. */ .factory('Friends', function($http) { ...

Cycle through the list and populate the table with the data

My attempt to clarify this explanation is my best, as articulating exactly what I am trying to achieve is quite challenging: Initially, I have a list of names: { "Items": [ { "Id": 0, "Name": "Robinson" }, ...

Utilize a randomized dynamic base URL without a set pattern to display a variety of pages

I am intrigued by the idea of creating a dynamic route that can respond to user-generated requests with specific files, similar to how Github handles URLs such as www.github.com/username or www.github.com/project. These URLs do not follow a set pattern, ma ...

Retrieve the visitor's IP address following the submission of an AJAX form

Currently, I am facing an issue with my HTML form and JavaScript method integration. Whenever a visitor submits the form, a JavaScript method is triggered which sends an AJAX request to a PHP file on my server. The problem arises when trying to retrieve ...

What is the purpose of having a constructor in Typescript when an interface is already used for a class?

Is it necessary to have a constructor in my class if the class already implements an interface? It seems like redundant code to me. interface PersonInterface { firstname: string; lastname: string; email: string; } class Person implements Pe ...

What is the reason behind the absence of the C++ syntax for a string loop in javascript?

UPDATE: At first, I believed that the following syntax was not functioning due to a mistake in my code and the fact that I have not encountered it being utilized in Javascript before. My primary concern lies in why this particular syntax is not more preval ...

Unusual issue with jQuery function failing to detect click events

As I delve into my first jQuery function, the primary goal is to assign a form to the function. Upon clicking the submit button, it should perform validation on each :input field within the function. The form is set as the selector for the function: $("f ...