How can I link JSON array data to a chart.js using the same canvas ID?

Here is the HTML Canvas code:

<div>
    <canvas id="chartdiv" width="200" height="200"></canvas>
</div>

Below is the JSON data:

[{
    "SID": "1",
    "NAME": "niten",
    "FTEPERCENT": "71.29",
    "FTCPERCENT": "28.71"
}, {
    "SID": "2",
    "NAME": "jiten",
    "FTEPERCENT": "82.08",
    "FTCPERCENT": "17.92"
}]

And here is the corresponding code snippet:

window.onload = function() {
    $.ajax({
        type: "POST",
        url: "ViewDirectManagersOverviewDetails.aspx/GetEmployeeOverviewDetailsForDirectManagers",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(Result) {
            debugger;
            Result = JSON.parse(Result.d);
            var newctx1;
            for (var i = 0; i < Result.length; i++) {

                var data1 = parseFloat(Result[i].FTEPERCENT);
                var data2 = parseFloat(Result[i].FTCPERCENT);
                var tempData = {
                    labels: ["FTE", "FTC"],
                    datasets: [{
                        data: [data1, data2],
                        backgroundColor: [
                            "#FF6384",
                            "#36A2EB"
                        ],
                        hoverBackgroundColor: [
                            "#FF6384",
                            "#36A2EB"
                        ],
                        borderWidth: 5
                    }]
                };
                // For a pie chart1
                var ctx = document.getElementById("chartdiv").getContext("2d");
                var myLineChart = new Chart(ctx, {
                    type: "pie",
                    data: tempData,
                    options: options,
                    title: {
                        display: true,
                        text: 'Employee Overview',
                        fontStyle: 'bold',
                        fontSize: 20
                    }
                });
            }
            $('chartdiv').append(newctx1);
        }
    });
};

The above code currently plots a pie chart on the same canvas ID using JSON data with two array objects. However, the requirement now is to plot separate pie charts on the same canvas ID but each representing different array object from the JSON.

This will involve looping through the JSON data and drawing separate pie charts in table rows to represent the data visually.

Answer №1

Regrettably, it's not possible to display multiple charts within one canvas using Chart.js. The library binds to the entire canvas object and utilizes the full canvas space to render a single chart.

If you wish to showcase two distinct pie charts, you will need two separate canvas elements. Nevertheless, you can include multiple datasets in a single graph if that better fits your requirements. In the case of a pie chart, it will embed a smaller pie chart inside a larger one.

Below is an example configuration demonstrating how to configure multiple datasets in a single pie chart:


var ctx = document.getElementById("chart-area").getContext("2d");
var myPie = new Chart(ctx, {
  type: 'pie',
  data: {
        labels: ["FTE", "FTC"],
    datasets: [{
      label: 'Dataset 1',
      data: data1,
      backgroundColor: [
        "#FF6384",
        "#36A2EB"
      ],
      hoverBackgroundColor: [
        "#FF6384",
        "#36A2EB"
      ],
      borderWidth: 5,
    }, {
      label: 'Dataset 2',
      data: data2,
      backgroundColor: [
        "#FF6384",
        "#36A2EB"
      ],
      hoverBackgroundColor: [
        "#FF6384",
        "#36A2EB"
      ],
      borderWidth: 5,
    }],
  },
  options: {
    title: {
     display: true,
      text: 'Employee Overview',
      fontStyle: 'bold',
      fontSize: 20
    }
  }
});

For further illustration, here is a codepen example.

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

ReactJS: The function .useSelector() is not defined

I've been following a tutorial for a while and hit a roadblock trying to understand this. Both metaphorically and literally. On the Dashboard page, I attempted to use useSelector() to access the state of the goalSlice component. This component is ver ...

Extract JSON data from a PHP web service

I have been searching extensively on the internet but have not found a proper solution yet. I am encountering an issue while sending JSON data from my android application to a PHP webservice. Oddly enough, when I test the webservice using the Advanced Res ...

How do I access HttpOnly cookies in an API request using Express?

Upon user login, a HttpOnly cookie is sent back in the response. https://i.sstatic.net/Rnsib.png However, when attempting to read the cookies during a subsequent API call, there seems to be nothing retrieved. This is how the cookie was created: var sig ...

What is the most effective method for defining 2 routes that point to the same component?

Although it may seem straightforward, I'm struggling to find the most efficient method for this particular scenario in Vue.js. I am using Vue Cli 3 and I need to have multiple routes leading to the same Home page within the application. The idea is ...

Activate an event on a separate webpage using jQuery or JavaScript

Currently, I am in the process of working on a project with 2 distinct pages: Index Settings On the Settings page, I have implemented a button to close an element and hide it. However, I am encountering an issue where I want the elements on the Index pa ...

Ways to retrieve data from every table in a database

I am currently facing an issue with fetching data from three columns located in different tables within a database. The tables have arbitrary names and I am struggling to formulate a query to retrieve information from these columns. Here is the query I ha ...

Invoking a Jquery function to access a webmethod via the $.ajax()

This is my first time using the $.ajax() function, so if you spot any errors, please let me know ;) I'm currently utilizing jQuery's $.ajax() to invoke a webmethod with JSON. The basic structure of the webmethod should resemble the following: ...

The path for Asp.net has been eliminated

My website is currently hosted on Network Solutions and functioning properly. I am attempting to create a test site on an old local server running Windows Server 2003. However, when I click on menu items in the site master, the pages are not loading from t ...

Converting a JavaScript variable to PHP for use with MySQL

Struggling to insert my Javascript variable "score" into a Mysql database, and it's not working as expected. Below is the code from Index.php: var score = 0; function post() { $.post('scoreadder.php',{uscore:score}, function(data){ consol ...

Having trouble getting the .each() method to function properly in jQuery

Looking for a solution to a similar issue here. Currently, I am attempting to iterate through multiple forms on a webpage and perform various actions with those forms. However, I am facing some challenges in making it work. Below is the code I am using: ...

A beginner's guide to extracting JSON data from Tweet.py outcomes

I've been attempting to parse the JSON file generated by Tweet.py, but no matter what I do, I keep running into a consistent ValueError. The error message reads: "ValueError: Expecting property name: line 1 column 3 (char 2)" The JSON results are st ...

You are unable to choose more than one file at a time for

Currently, I am in the process of developing an application using HTML, CSS, and JS by following a tutorial. The main purpose of this app is to merge multiple PDF files together. However, I have encountered an issue where I am unable to select multiple fil ...

Transforming a JSON schema into a C# class

I am new to JSON but have some knowledge in C#. I have a JSON schema where I encountered a section that I'm unsure how to incorporate into the objects class. "def_subscore": { "type": "number", "minimum": 0, "maximum": 10 }, "def_impact": ...

The Aurelia application named "Greetings Earth" is experiencing complete malfunction

As I embark on creating a Sharepoint framework webpart, my aim is to incorporate Aurelia as the JavaScript framework. The process begins with generating a Sharepoint framework webpart using Yeoman, resulting in this folder structure. Here are the core fi ...

Flickity remains in plain sight on desktop devices

I am trying to hide the flickity slider on desktop and larger devices. I have followed the instructions in the documentation, but for some reason, it's not working as expected. Here is how the div looks: <div class="w-full flex pl-4 pb-16 overflo ...

What is the advantage of using a foreach loop to overwrite values instead of returning all values?

Here is an array that needs to be stored in local storage when the DOM is created. this.headers.push( { text: "Name", align: "center", sortable: true, value: "name", align: "start&q ...

Execute a JavaScript function when an element loaded via Ajax in a Spring MVC framework triggers the onChange event

I currently have a dropdown list with two values and I am looking to enable or disable four components based on the user's selection. If the user picks the first value, the components should be enabled, otherwise they should be disabled. On the main ...

Persist an array of objects to a MongoDB database by utilizing Node.js and Express framework

I have been attempting to preload an array of objects into MongoDB in the following manner: The code provided below functions properly when I load one object at a time. For instance, If I define: tmp_obj = { id:1, name: 'Tmp 1' } Mode ...

What is the most effective method for declaring a constant within a WebComponent?

After receiving questions, I included more details on how I'm utilizing the constants. The main issue I am encountering is that the constants are being added to the global object, which raises concerns about potential name collisions. I created a Web ...

Fade in and out of page or div elements with a simple click

I've been dedicating some time to my recruitment website lately. As a beginner in coding, I'm looking for a script that will automatically fade out the Employment review content when clicking on each employment vacancy div and then fade back in w ...