Is there a way to simultaneously modify several data variables within a Chart.js label?

I'm currently working on dynamically updating a line chart with two data entry points using the variable name "data."

Take a look at the code snippet below:

var lion = new Chart(ctx2, {
      type: "line",
      data: {
        labels: ["Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
        datasets: [{
            label: "Mobile apps",
            tension: 0.4,
            borderWidth: 0,
            pointRadius: 0,
            borderColor: "#cb0c9f",
            borderWidth: 3,
            backgroundColor: gradientStroke1,
            fill: true,
            data: [50, 40, 300, 220, 500, 250, 400, 230, 500],
            maxBarThickness: 6

          },
          {
            label: "Websites",
            tension: 0.4,
            borderWidth: 0,
            pointRadius: 0,
            borderColor: "#3A416F",
            borderWidth: 3,
            backgroundColor: gradientStroke2,
            fill: true,
            data: [30, 90, 40, 140, 290, 290, 340, 230, 400],
            maxBarThickness: 6
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: false,
          }
        },
        interaction: {
          intersect: false,
          mode: 'index',
        },
        scales: {
          y: {
            grid: {
              drawBorder: false,
              display: true,
              drawOnChartArea: true,
              drawTicks: false,
              borderDash: [5, 5]
            },
            ticks: {
              display: true,
              padding: 10,
              color: '#b2b9bf',
              font: {
                size: 11,
                family: "Open Sans",
                style: 'normal',
                lineHeight: 2
              },
            }
          },
          x: {
            grid: {
              drawBorder: false,
              display: false,
              drawOnChartArea: false,
              drawTicks: false,
              borderDash: [5, 5]
            },
            ticks: {
              display: true,
              color: '#b2b9bf',
              padding: 20,
              font: {
                size: 11,
                family: "Open Sans",
                style: 'normal',
                lineHeight: 2
              },
            }
          },
        },
      },
    });

I attempted to dynamically update using the following method:

 setInterval(function(){ 
    // The code inside this block will run every 2 seconds.    

    lion.data.datasets[0].data = [getRandomInt(100), getRandomInt(100), getRandomInt(100),getRandomInt(100),getRandomInt(100),getRandomInt(100),getRandomInt(100),getRandomInt(100),getRandomInt(100)],
// Finally, update the chart:
lion.update();

}, 2000);

This code snippet updates the data variables every 2 seconds.

However, I found that it only updates the data for the "websites" dataset and not for both labels as expected.

How can I target and update both data variables for both labels simultaneously?

Answer №1

Make sure to update all datasets, not just the initial one.

setInterval(function() {
  // Add code here that runs every 5 seconds.

  lion.data.datasets[0].data = [getRandomInt(100), getRandomInt(100), getRandomInt(100), getRandomInt(100), getRandomInt(100), getRandomInt(100), getRandomInt(100), getRandomInt(100), getRandomInt(100)];
  lion.data.datasets[1].data = [getRandomInt(100), getRandomInt(100), getRandomInt(100), getRandomInt(100), getRandomInt(100), getRandomInt(100), getRandomInt(100), getRandomInt(100), getRandomInt(100)];
  // Update the chart:
  lion.update();

}, 2000);

You can also iterate over them instead of hardcoding:

setInterval(function() {
  // Add code here that will be run every 5 seconds.    

  lion.data.datasets.forEach(dataset => dataset.data = [getRandomInt(100), getRandomInt(100), getRandomInt(100), getRandomInt(100), getRandomInt(100), getRandomInt(100), getRandomInt(100), getRandomInt(100), getRandomInt(100)]);
  // Update the chart:
  lion.update();

}, 2000);

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 persistent issue persists with the Sails.js Node server where the req.session remains devoid of any data, despite utilizing

Currently, I have an Ember app running on http://localhost:4200 and a Sails app running on http://localhost:1337. In order to set up a pre-signup survey policy in my Sails application, I have the following code in /api/controllers/ProcessSurveyController. ...

What is the best way to change an HTML class using PHP?

I'm currently facing a challenge with my "Newsletter Subscription Form". I rely on MailChimp for sending out newsletters and have successfully set up a custom PHP file to redirect visitors after they enter their email. Here's the step-by-step pr ...

Looking for a way to identify when a DOM element is resized as a result of web fonts loading asynchronously?

Within this div element lies text styled with a custom font via CSS's @font-face attribute. The issue arises when the font hasn't loaded yet, causing a delay in updating the font style of the text within the div. As a result, taking measurements ...

Chrome's inability to efficiently handle chunked responses in comparison to Firefox and Safari

I am currently working on a unique test node server that sends chunked responses every two seconds with the specified headers: response.setHeader('Content-Type', 'text/plain') response.setHeader('Transfer-Encoding', 'chu ...

404 Error: JSON POST and GET Request Not Located

I need assistance with setting up an API in Django as I am encountering errors in the JavaScript console. The error messages are: GET http://127.0.0.1:8000/edit/undefined 404 (Not Found) POST http://127.0.0.1:8000/edit/undefined 404 (Not Found) Is there a ...

The middleware code remains dormant and is left untouched

I am encountering an issue with this code that is supposed to create a folder if it doesn't already exist. When I debug and set a breakpoint on fs.mkdir, the code does not enter into it. Do you have any idea what could be causing this problem? ... ap ...

Encountering an issue with executing Google API Geocode in JavaScript

I'm having trouble printing an address on the console log. Every time I run the code, I encounter an error message that reads: { "error_message" : "Invalid request. Missing the 'address', 'components', 'latlng' or &ap ...

What emerging patterns can be observed in the security of client-side coding within the realm of web development

Keeping up with the constant flow of new frameworks and technologies can be overwhelming. One area that particularly interests me is client-side frameworks, such as AngularJS, Backbone, Knockout, jsviews, knockback, SPA... These are currently among the mos ...

Results don't align with search parameters

const searchClientes = (event) => { if (event.target.value === '') { getClientes(); return; } else { const searchTerm = event.target.value; const filteredClients = clientes.filter(cliente => { return cliente.nome ...

Creating distinct identifiers for table cells utilizing the map function

Is there a way to assign a unique id to each MenuItem using the map() function nested within another one? <table className={classes.table}> <thead> <tr> <td /> {sit.sit.map(sit => ( <td className={ ...

In the React js and emotion framework, fonts are only loaded in production mode after the page has been re

I have set up emotion's Global component to globally apply a font to my app: export const GlobalStyle: FC<{}> = () => ( <Global styles={css` @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@100;300;400;50 ...

Is there a discrepancy in performance when running a function on an individual element versus a group of elements within jQuery?

Imagine having the choice between applying a function to an individual DOM element or a list of them: For Individual Elements: $('#element1').click(function () { $(this).hide(); return false; }); $('#element2').click(functi ...

Error: Angular2 RC5 | Router unable to find any matching routes

I am currently encountering an issue with my setup using Angular 2 - RC5 and router 3.0.0 RC1. Despite searching for a solution, I have not been able to find one that resolves the problem. Within my component structure, I have a "BasicContentComponent" whi ...

Obtain the date in ISO format without subtracting the timezone offset

I need to obtain a Date string without the timezone being added or subtracted. Currently, when I set my OS timezone to GMT +13 and create a new Date() object, the toISOString() method subtracts one day. For example, today is 11/02. If I adjust my OS time ...

Using node appendChild() in HTML for animating elements

As someone who is brand new to the world of web development, I am trying my hand at creating a webpage that expands as a button is clicked. Recently, I stumbled upon this helpful link which includes some code: The HTML code snippet is: <ul id="myList" ...

Is it possible to delete browsing history in Express using node.js?

Upon user login, I store user information in browser sessions on the client side (using Angular) like this: $window.sessionStorage.setItem('loggedInUser', JSON.stringify(val)); For logout authentication on the backend (using Passportjs), I have ...

Service for Posting in Angular

I am looking to enhance my HTTP POST request by using a service that can access data from my PHP API. One challenge I am facing is figuring out how to incorporate user input data into the services' functionality. Take a look at the following code snip ...

Retrieving properties from a selector's output function

My situation is similar to the scenario described in the accessing react props in selectors documentation. However, in my case, let's assume that the visibilityFilter is coming from the props. Is there a way to achieve something like the following? e ...

The function getComputedStyle(elem).getPropertyValue('fontSize') returns incorrect values when the font size of the element is specified in em units

My current issue involves trying to obtain the font size of an element in the following manner: getComputedStyle(MyTargetElement , "").getPropertyValue('font-size') The result is coming back as 16px, when it should actually be 14px. W ...

Is it possible to create a development build using Npm with React and Typescript?

I have successfully set up a TypeScript React app by using the command below: npx create-react-app my-app --template typescript However, running "npm start" generates development javascript files and launches a development server which is not id ...