Guide on creating dynamic datasets and multiple dynamic yAxes

To enhance my chart, I am interested in adding multiple Y Axes based on the examples provided below: script 1 script 2

Although I attempted to modify the code as shown below, it seems to not be functioning properly.

function rdnum() {
  return Math.floor(Math.random() * 100);
}

var config = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: []
  },
  options: {
    scales: {
      yAxes: []
    }
  }
}
var i = 0;
var x;

var ctx = document.getElementById('chartJSContainer').getContext('2d');
var chart = new Chart(ctx, config);


addNewYAxe = function() {
  x = Date.now();

  let newDataset = {
    label: 'test' + '_' + i,
    data: [],
    yAxisID: "left" + x,
    fill: false
  };
  for (let index = 0; index < 6; ++index) {
    newDataset.data.push(rdnum());
  }

  chart.data.datasets[i] = newDataset;
 
  console.log(chart.data.datasets);

  let y = {};
  chart.options.scales.yAxes[i] = y;

  let y2 = chart.options.scales.yAxes[i];
  y2.display = true;
  y2.type = "linear";
  y2.id = "left" + x;
  y2.position = "right";
  i++;

  console.log(chart.options.scales.yAxes);

  chart.update();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="addNewYAxe()">add new Y axe</button>
<canvas id="chartJSContainer" width="600" height="400"></canvas>

In order to dynamically insert specific data sets and Y axis using a button, where each click adds a new dataset and Y axis to the chart, I have tried merging two example codes together but encountered errors.

Answer №1

The issue lies within the version of chart.js being used. Updating to the latest version (2.9.3) resolves this problem.

function generateRandomNumber() {
  return Math.floor(Math.random() * 100);
}

var configuration = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: []
  },
  options: {
    scales: {
      yAxes: []
    }
  }
}
var count = 0;
var timestamp;

var context = document.getElementById('chartJSContainer').getContext('2d');
var newChart = new Chart(context, configuration);


addNewYAxis = function() {
  timestamp = Date.now();

  let newData = {
    label: 'test' + '_' + count,
    data: [],
    yAxisID: "left" + timestamp,
    fill: false
  };
  for (let index = 0; index < 6; ++index) {
    newData.data.push(generateRandomNumber());
  }

  newChart.data.datasets[count] = newData;

  let yAxis = {};
  newChart.options.scales.yAxes[count] = yAxis;

  let yAxis2 = newChart.options.scales.yAxes[count];
  yAxis2.display = true;
  yAxis2.type = "linear";
  yAxis2.id = "left" + timestamp;
  yAxis2.position = "right";
  count++;

  newChart.update();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="addNewYAxis()">Add New Y Axis</button>
<canvas id="chartJSContainer" width="600" height="400"></canvas>

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

What are some ways to design unique custom data grid toolbar elements?

I am having trouble syncing my custom toolbar buttons with the imported material data grid toolbar components. I would like them to match in style, specifically applying the material styles to my custom components. However, I have not been able to find a w ...

I'm experiencing a problem when trying to add a document to Firebase Firestore using React Native - it doesn't seem to

I'm currently working on a React Native project that utilizes Firebase v9. My goal is to add a user object to my user collection whenever a new user signs up through the sign-up screen. However, I've encountered an issue where the user object is ...

Is it possible to achieve a file upload in splinter using Python?

A challenging task lies ahead with my web application, where users can upload XML-style files and make modifications directly in the browser. To test this scenario using Splinter, I need to ensure correct input (id="form-widgets-body"): https://i.sstatic ...

Ways to extract certain characters from each element in an array

I'm attempting to make the first four characters of each element in an array (specifically a list) bold, but I am only able to select entire strings: $("li").slice(0).css("font-weight", "Bold"); Is there a way for me to indicate which characters wit ...

Step-by-step guide on creating a login functionality in Node using the Mean.io stack

I'm currently working on a web app using the MEAN.io stack. I have completed the frontend part with HTML, CSS, and AngularJS along with some logic. Now, I am looking to implement server-side login functionality, but I'm unsure where to begin sinc ...

Using Angular's ngBlur directive on multiple input fields

My current task involves capturing and saving all content on a webpage after it has been edited. For example, when a user clicks into an input field, enters data, and then clicks elsewhere, I would like to trigger a function to collect all the model data a ...

The some() method in Javascript with an extra argument

I want to validate if at least one element in an array satisfies a certain condition. The condition is based on a variable. Here's an example of how I'm currently attempting this: function checkCondition(previousValue, index, array) { retur ...

Tips for including type definitions when adding elements to an array in TypeScript

Having trouble avoiding the use of 'any' as the type definition when pushing elements into an array? I attempted to specify the type but encountered an error. Here is a snippet of the code: interface answerProps { state: string; answer: s ...

Unable to produce audio from files

Attempting to incorporate sound files into my project using https://github.com/joshwcomeau/redux-sounds but encountering difficulties in getting it to function. Below is the code snippet I utilized for setup. Unsure if webpack is loading the files correctl ...

iOS devices will not scroll horizontally if there is a div that scrolls vertically within a div that scrolls horizontally

Picture a div that scrolls horizontally, housing two vertical-scrolling divs. You'll need to scroll left and right to navigate, then up and down inside the inner divs to read the content. /* RESET TO MINIMUM */ body, html { height: 100%; mar ...

Having trouble with errors when adding onClick prop conditionally in React and TypeScript

I need to dynamically add an onClick function to my TypeScript React component conditionally: <div onClick={(!disabled && onClick) ?? undefined}>{children}</div> However, I encounter the following error message: Type 'false | (() ...

Using Next.js to pass fetched data as props to components

I am currently working on integrating a leaflet map into my Next.js project. The map display is already functioning with predefined latitude and longitude in the component. However, I now need to show data retrieved from my API as the longitude and latitu ...

Creating a JQuery statement to conditionally change CSS values

Is there a way to determine if a div element with a CSS class of "x" has a height set to "auto"? If so, I would like a jQuery script to remove the CSS class "a" from all elements with the class "y". If not, the script can remain unchanged. Thank you. ...

What is preventing the visibility of my invoice items when I try to make edits to my invoice?

Currently, I am utilizing Laravel 5.7 and VueJs 2.5.* in my project. The issue I am facing is related to a Bootstrap Model that I use for creating and editing TicketInvoice and its associated TicketInvocieItems. When I try to edit, the Bootstrap Model open ...

Spinning html/css content using JavaScript

Greetings! I am currently working on a demo site using just HTML, CSS, and JavaScript. Typically, I would use Ruby and render partials to handle this issue, but I wanted to challenge myself with JavaScript practice. So far, I have created a code block that ...

Does this information operate on Vue or Node?

I have recently started learning programming and currently working on an HTML project for school. My professor mentioned that we should only use Node.js for this project. However, I am concerned that the function I used below might be Vue instead of Node ...

Struggling to bring in { useActionState } from 'react' while trying to follow the latest next.js tutorial with next.js v15.0.0-canary.28, react v19.0.0-rc, and types/react v18.2.21

Currently, I am following the tutorial on next.js available at https://nextjs.org/learn/dashboard-app I have reached chapter 14, which focuses on enhancing accessibility, located at https://nextjs.org/learn/dashboard-app/improving-accessibility During on ...

Even with employing Cors alongside Axios, I continue to encounter the following issue: The requested resource does not have the 'Access-Control-Allow-Origin' header

When working with a MEAN stack app, I had no issues with CORS. However, upon transitioning to the MERN stack, I encountered an error related to CORS despite having it implemented in the backend: Access to XMLHttpRequest at 'http://localhost:5000/api/ ...

Error encountered: iPad3 running on iOS7 has exceeded the localStorage quota, leading to a

Experiencing a puzzling issue that even Google can't seem to solve. I keep getting the QuotaExceededError: DOM Exception 22 on my iPad3 running iOS7.0.4 with Safari 9537.53 (version 7, WebKit 537.51.1). Despite turning off private browsing and trying ...

Stop the background from scrolling and prevent auto-jumping to the top on mobile devices

When users click on the hamburger icon in the top right of our mobile site, I want the drop-down menu to appear and be scrollable without the background scrolling. I tried using JavaScript to set the body to fixed when the menu icon is clicked, but this ca ...