Steps for placing a second pie chart alongside the initial one within a Bootstrap card

Is it possible to have two pie charts with different values using chart.js? I attempted to duplicate the script for the first chart to create a second one, but it did not display correctly. Why is the second pie chart not showing up?

  $(document).ready(function() {
    var ctx = $("#chart-line");
    var myLineChart = new Chart(ctx, {
        type: 'pie',
        data: {
            labels: ["Spring", "Summer", "Fall", "Winter"],
            datasets: [{
                data: [1200, 1700, 800, 200],
                backgroundColor: ["rgba(255, 0, 0, 0.5)", "rgba(100, 255, 0, 0.5)", "rgba(200, 50, 255, 0.5)", "rgba(0, 100, 255, 0.5)"]
            }]
        },
        options: {
            title: {
                display: true,
                text: 'Weather'
            }
        }
    });
});
$(document).ready(function() {
    var ctx = $("#chart-line");
    var myLineChart = new Chart(ctx, {
        type: 'pie',
        data: {
            labels: ["Spring", "Summer", "Fall", "Winter"],
            datasets: [{
                data: [1200, 1700, 800, 200],
                backgroundColor: ["rgba(255, 0, 0, 0.5)", "rgba(100, 255, 0, 0.5)", "rgba(200, 50, 255, 0.5)", "rgba(0, 100, 255, 0.5)"]
            }]
        },
        options: {
            title: {
                display: true,
                text: 'Weather'
            }
        }
    });
});

Here is the HTML code:

                <div class="page-content page-container" id="page-content">
                    <div class="padding">
                        <div class="row">
                            
                                <div class="col-md-6">
                                    <div class="card">
                                        <div class="card-header">Pie chart</div>
                                        <div class="card-body" style="height: 400px">
                                            <div class="chartjs-size-monitor" style="position: absolute; left: 0px; top: 0px; right: 0px; bottom: 0px; overflow: hidden; pointer-events: none; visibility: hidden; z-index: -1;">
                                                <div class="chartjs-size-monitor-expand" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;">
                                                    <div style="position:absolute;width:1000000px;height:1000000px;left:0;top:0"></div>
                                                </div>
                                                <div class="chartjs-size-monitor-shrink" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;">
                                                    <div style="position:absolute;width:200%;height:200%;left:0; top:0"></div>
                                                </div>
                                            </div> 
                                            
                                            <canvas id="chart-line" width="399" height="400" class="chartjs-render-monitor" style="display: block; width: 400px; height: 500px;"></canvas>
                                        </div>
                                    </div>
                                </div>
                            `

Answer №1

If you want to display the same chart twice, it's a good idea to extract the chart codes into a separate function.

$(document).ready(function() {
   renderChart($("#chart-line"));
   renderChart($("#chart-line2"));
})

function renderChart(ctx) {
    var myLineChart = new Chart(ctx, {
        type: 'pie',
        data: {
            labels: ["Spring", "Summer", "Fall", "Winter"],
            datasets: [{
                data: [1200, 1700, 800, 200],
                backgroundColor: ["rgba(255, 0, 0, 0.5)", "rgba(100, 255, 0, 0.5)", "rgba(200, 50, 255, 0.5)", "rgba(0, 100, 255, 0.5)"]
            }]
        },
        options: {
            title: {
                display: true,
                text: 'Weather'
            }
        }
    });
};

To display the additional chart, add another canvas element in your html with a different id.

<canvas id="chart-line" width="399" height="400" class="chartjs-render-monitor" style="display: block; width: 400px; height: 500px;"></canvas>
<canvas id="chart-line2" width="399" height="400" class="chartjs-render-monitor" style="display: block; width: 400px; height: 500px;"></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

Guide to establishing a connection with a Node.js socket server

I'm delving into the world of node JS and experimenting with creating a real-time application that involves a node JS server using socket.io, along with a unity application that can communicate with it. Below is the code I used to set up the server w ...

To access the link, simply click once if there is no child menu. However, if there is a child menu attached, be sure to click

I am working on a mobile menu that is designed to slide out when clicked. Currently, the parent pages are displayed by default. I want to implement functionality where if a parent page has child pages, clicking on it will slide down the sub menu. If click ...

step by step guide on swapping a portion of a JSON string

I need to eliminate the character "C" from keys that start with C_ in the following JSON string. Here is the JavaScript object I have: var jsonData= { key1:val1, key2:val2, C_100:1, C_101:2, C_102:3, } The desired output should look like this: v ...

Effective ways to transmit a variable array from an HTML document to a PHP server

Is there a better method for transferring a variable array from HTML to PHP? I attempted to use the serialize function, but it doesn't seem to be functioning correctly. Any suggestions would be greatly appreciated. //HTML var arrayTextAreasNames = [ ...

What is the syntax for utilizing cookies within the `getServerSideProps` function in Next.js?

I am struggling to pass the current language to an endpoint. Despite attempting to retrieve the language from a Cookie, I keep getting undefined within the getServerSideProps function. export async function getServerSideProps(context) { const lang = aw ...

Encountering a NextJS error when attempting to access a dynamic route

I am currently working on a Next.js application that involves dynamic routing. I have encountered an error message stating: Error: The provided path X0UQbRIAAA_NdlgNdoes not match the page:/discounts/[itemId]`.' I suspect that the issue may be relat ...

JavaScript bug with URL encoding in Internet Explorer 11

I am encountering an issue with Internet Explorer 11 (IE 11) when attempting to call a JavaScript URL function. The problem lies with the URL parameter value, which is in Unicode format but the result displays as ????? instead of Unicode characters. Belo ...

How can I create a table using a loop and an onclick function for each <td>?

I have written code to create a table in PHP using a loop. I want to add an onclick function to each cell so that when a particular cell is clicked, the background color changes. However, I am encountering an error. Am I doing something wrong? <head& ...

I am interested in displaying the PDF ajax response within a unique modal window

With the use of ajax, I am able to retrieve PDF base64 data as a response. In this particular scenario, instead of displaying the PDF in a new window, is it possible to display it within a modal popup? Any suggestions on how this can be achieved? $.ajax ...

Divide text to reduce its width within the confines of a specific height on a div element

I've spent the past week scouring various forums, including stackoverflow, but I haven't been able to find a solution. In my responsive website, I'm using CSS flexbox to display dynamic menu items. Sometimes the text can be quite long, and ...

What is the correct process for authenticating requests from SSR to the Feathers JS API?

There are some examples available on how to access FeathersJS API from SSR, but the important aspect of authorizing such requests is missing. Is it feasible to create a feathers-client app for each request? Wouldn't that put too much load on the syste ...

Steps to dynamically modify an HTML element within an Android WebView

https://www.bing.com/search?q=кму here I want to switch the bing icon to google I attempted : if (url == "https://www.bing.com/search?q=") { view.evaluateJavascript( ("\n"+ "wind ...

Using the v-for directive in Vue.js to loop through an array and display

Looking at the image provided, I am trying to access the content. I attempted to do so using element.comments.content, but it did not seem to work as expected. Here is the snippet of code: <div class="fil-actualites-container"> <div cl ...

What is the best way to incorporate custom events into classes using Node.js?

Recently delving into node, I have a question about adding custom events to a class. In the code below, I attempted to create a simple farm class where the number of animals changes and triggers an event called totalChanged. let events = require('eve ...

Tips for successfully implementing Angular.js validation within the confines of a <form> element

Having trouble getting my code to work when I place my app inside the <form name="myForm"> tag. Any suggestions on how to make it function properly? (It works when I place myForm inside ng-app, but my app needs to be within the <form> tag) < ...

Is there a way to retrieve nested data from a JSON API response?

Trying my hand at creating a basic CLI cryptocurrency tracker app. The app runs a successful API call and provides the following output: [ { exchange: 'binance', base: 'ADA', quote: 'BTC', price_quote: '0.000 ...

How can I identify the appropriate default option element in AngularJS?

Query: I have a scenario where I need to set the default option in an angular dropdown menu based on values from an array of Person objects. How can I achieve this when initially loading the UI? http://plnkr.co/edit/hvIimscowGvO6Hje35RB?p=preview <!DO ...

What is the appropriate HTTP status code for "item not found" when using RESTful ajax?

Imagine having a single-page web application featuring a list of items. Users can click on an item to view more information about it. The details of each item are loaded asynchronously via an AJAX GET request to the URL http://www.example.com/item/[id], an ...

How to delete an element from a session array using Jquery and Ajax techniques

In my table, each element in an array corresponds to a row. I'm attempting to delete an element when the delete image (with the id deleteRowButton) is clicked. Currently, nothing happens upon clicking the image. However, if I remove the line var index ...

Utilizing AngularJS for Converting Date Formats from JSON and HTML Elements

So I have this controller set up. function TestCtrl($scope) { var contentFromJson = 'Hi! this is <b>Bold</b> and <i>Italic</i>'; var dateFromJson = '/Date(1394526738123)/'; $scope.Date = dateFromJso ...