In what way can I indicate parsing "per dataset" using Chart.js?

I'm currently exploring the usage of the yAxisKey option in ChartJS while defining a dataset. However, I'm encountering difficulties in replicating this specific example from the documentation. Despite my efforts to search for issues related to yAxisKey (or xAxisKey), the parsing options, and general information on specifying datasets, I have yet to find a solution.

Here's an example:

<!doctype html>
<html>
<head>
    <title>Sample Chart</title>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f4979c958680da9e87b4c6daccdac4">[email protected]</a>"></script>
</head>

<body>
    <canvas id="canvas"></canvas>
    <script>
        const data = [{x: 'Jan', net: 100, cogs: 50, gm: 50}, {x: 'Feb', net: 120, cogs: 55, gm: 75}];
        const config = {
                type: 'bar',
                data: {
                    labels: ['Jan', 'Feb'],
                    datasets: [{
                        label: 'Net sales',
                        data: data,
                        parsing: {
                            yAxisKey: 'net'
                        }
                    }, {
                        label: 'Cost of goods sold',
                        data: data,
                        parsing: {
                            yAxisKey: 'cogs'
                        }
                    }, {
                        label: 'Gross margin',
                        data: data,
                        parsing: {
                            yAxisKey: 'gm'
                        }
                    }]
                },
            };

        window.onload = function() {
            const ctx = document.getElementById('canvas').getContext('2d');
            let chart  = new Chart(ctx, config);
        };
    </script>
</body>
</html>

Despite following the code, I end up with a chart that appears empty.

https://i.sstatic.net/02kkA.png

Could I be overlooking something obvious or misunderstanding the syntax?

Thank you in advance!

Answer №1

As the per-dataset parsing option is currently not supported in the version of Chart.js you are using (2.8.0), you can achieve the same outcome using the Array.map() function.

Please review your updated code to see how it functions.

<!doctype html>
<html>

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

<body>
  <canvas id="canvas"></canvas>
  <script>
    const data = [
      { x: 'Jan', net: 100, cogs: 50, gm: 50 }, 
      { x: 'Feb', net: 120, cogs: 55, gm: 75 }
    ];
    const config = {
      type: 'bar',
      data: {
        labels: data.map(o => o.x),
        datasets: [{
          label: 'Net sales',
          data: data.map(o => o.net)
        }, {
          label: 'Cost of goods sold',
          data: data.map(o => o.cogs)
        }, {
          label: 'Gross margin',
          data: data.map(o => o.gm)
        }]
      },
      options: {
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }]
        }
      }
    };

    window.onload = function() {
      const ctx = document.getElementById('canvas').getContext('2d');
      let chart = new Chart(ctx, config);
    };
  </script>
</body>

</html>

Answer №2

It seems that the option for per-dataset parsing will be included in the upcoming release of Chart.js version 3.0.0. Currently, the stable version available is 2.9.3.

We recommend testing your code with Chart.js 3.0.0 alpha-2 to see how it functions.

<!doctype html>
<html>
<head>
    <title>Example Chart</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.0-alpha.2/chart.min.js"></script>
</head>

<body>
    <canvas id="canvas"></canvas>
    <script>
        const data = [{x: 'Jan', net: 100, cogs: 50, gm: 50}, {x: 'Feb', net: 120, cogs: 55, gm: 75}];
        const config = {
                type: 'bar',
                data: {
                    labels: ['Jan', 'Feb'],
                    datasets: [{
                        label: 'Net sales',
                        data: data,
                        parsing: {
                            yAxisKey: 'net'
                        }
                    }, {
                        label: 'Cost of goods sold',
                        data: data,
                        parsing: {
                            yAxisKey: 'cogs'
                        }
                    }, {
                        label: 'Gross margin',
                        data: data,
                        parsing: {
                            yAxisKey: 'gm'
                        }
                    }]
                },
            };

        window.onload = function() {
            const ctx = document.getElementById('canvas').getContext('2d');
            let chart  = new Chart(ctx, config);
        };
    </script>
</body>
</html>

Answer №3

By simply swapping out the content delivery network, your current code should continue to function seamlessly

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

Unable to display Boostrap modal upon clicking href link

Can someone help me troubleshoot why my pop modal is not displaying after a user clicks on a specific link on my webpage? I have attempted the following: <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></s ...

What could be causing the malfunction in this JavaScript and WebRTC code?

<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Vid Chat App</title> </head> <body> <video controls autoplay> </video> <script src="https: ...

Learning the basics of JavaScript: Displaying the last number in an array and restarting a function

Hey there, I'm diving into the world of JavaScript and have set myself a challenge to create a simple bingo number machine. Check out my CodePen project here. I've successfully generated an array of 20 numbers, shuffled them, and added a marker t ...

Understanding the process of globally evaluating classes from files in node.js using the Eval function

Parent script with childscript integration const fs = require('fs'); function includeFile(f) { eval.apply(global,[fs.readFileSync(f).toString()]) } includeFile(__dirname+'/fileToRead.js'); hi(); ...

Rails application experiencing difficulties in displaying the Raty JS plugin

Encountering issues with the raty js plugin while working on Rails version 5.0. jquery.raty.self-628421be04f36f7a8fa8b9b884c6d7824d6f8bdeba4f172b131f15aa63f713e8.js?body=1:761 Uncaught ReferenceError: jQuery is not defined at jquery.raty.self-628421be ...

Tips for including an additional class in an element

I have an image tag with the "kiwi" class, and another class that makes it spin. I want to toggle this second class (called 'elem') when clicking on the play button of my music player. Here is the image tag with the class: <img src="./im ...

Assigning a session variable through a dropdown selection

Currently, I am working on a custom WordPress theme that involves setting a session variable based on the value selected from a dropdown box. This session variable is then used to determine which container should be loaded. The code snippet below shows whe ...

Utilize the Spotify API to discover tracks by including the album title and artist's name in the search

Currently working on a project that involves searching for a music track on Spotify. The idea is to input the track name in the text area and generate a list of matching Track IDs along with Artist Names, Album Names, and Artwork. I have made some progress ...

Issues with Semantic UI Calendar not displaying properly

I am currently experimenting with the Semantic UI Calendar, where there is a date input field and a calendar that pops up when selected as demonstrated in this initial example. Since I am not familiar with this process, I am uncertain if I have properly li ...

Struggling with Implementing jQuery for Triggering Multiple Functions on a Single Change Event?

I am currently developing jQuery functions that create dependencies between the css classes of different inputs in a web form. For example, when a specific input has a certain value, the "hide" class is removed from another input. One working example of t ...

Using Vue.js to create numerous modal popups

Currently, I am using Vue.JS for a research project at my workplace. My focus right now is mainly on the front-end. I have a table with several entries, and when a row is clicked, I want a modal popup window to display further details about that specific ...

The jQuery click event is failing on the second attempt

My PHP code dynamically generates a list, and I want to be able to delete rows by clicking on them. The code works fine the first time, but not the second time. HTML <li> <div class="pers-left-container"> <img src="<?php ech ...

Is it possible to utilize Ajax submit requests within a (function($){...}(jQuery)); block?

As a PHP developer with some knowledge of JavaScript, I am currently using AJAX to send requests to the server. I recently came across the practice of enclosing all code within an anonymous JavaScript function like: (function($){ //code here }(jQuery)). Fo ...

Guide to using Ajax to load a partial in Ruby on Rails

Whenever a search is triggered, I have a partial that needs to be loaded. This partial can take a significant amount of time to load, so I would prefer it to be loaded via Ajax after the page has fully loaded to avoid potential timeouts. Currently, my app ...

Unable to trigger dispatchEvent on an input element for the Tab key in Angular 5

In my pursuit of a solution to move from one input to another on the press of the Enter key, I came across various posts suggesting custom directives. However, I prefer a solution that works without having to implement a directive on every component. My a ...

Passing data between parent and child components within an Angular application using mat tab navigation

I am currently working on a project, which can be found at this link. Current Progress: I have implemented a mat tab group with tabs inside the app-component. When a tab is clicked, a specific component is loaded. Initially, most of the data is loaded in ...

What is the reason behind JSLint's preference for x === "undefined" over typeof x == "undefined"?

I'm feeling lost when it comes to JSLint. Initially, my code checked if div:jqmData("me") was undefined in this way: if ( typeof el.jqmData("me") == "undefined" ? el.not(':jqmData(panel="main")').length > 0 : el.not(':jqm ...

Guide to activating a function by tapping anywhere on a webpage in iPhone Safari

I am attempting to implement a jQuery function that will change the text of a div in the iPhone browser when any area of the page is clicked. Here is my current setup: <div id="alternative_text">traduit</div> <script type="text/javascript ...

steps for using the push method to create a new array in JavaScript

Currently, I am attempting to create a new array that is similar to the myCourses array using the push method. However, for some reason it only seems to be logging one string at a time instead of generating a new array that mirrors the myCourses array: ...

Complete Search with the press of Enter on the Auto Textbox

I have implemented an Ajax auto complete extender on a TextBox control. As the user begins typing, suggestive options are displayed below the input field based on data retrieved from a webservice call. When OnClientItemSelected="GetCode" is triggered, the ...