简体   繁体   中英

Inserting data from arrays into a pie chart (chart.js)

I have 2 arrays of data that I want to insert into a pie chart.

so I have this code:

new Chart(document.getElementById("pie-chart"), {
    type: 'pie',
    data: {
      labels: ["Africa", "Asia", "Europe", "Latin America", "North America"],
      datasets: [{
        label: "Population (millions)",
        backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
        data: [2478,5267,734,784,433]
      }]
    },
    options: {
      title: {
        display: true,
        text: 'Predicted world population (millions) in 2050'
      }
    }
});

Instead of writing the label and data, I want to get this information from 2 arrays (one for labels and one for data). How can I do it?

Please use the following jsfiddle, created for you, this might help you.

https://jsfiddle.net/ua5hsj7k/

<!DOCTYPE html>
<html>
<head>
<title>ChartJS - Pie</title>
<link type="text/css" rel="stylesheet" href="css/default.css" />
</head>
<body>
<div class="chart-container">
<div class="pie-chart-container">
  <canvas id="pie-chartcanvas-1"></canvas>
</div>


  </div>

   <!-- javascript -->
   <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
  </body>
   </html>

# code in js file

    var piechart = $("#pie-chartcanvas-1");

   var data1 = {
   labels: ["Africa", "Asia", "Europe", "Latin America", "North America"],
   datasets: [
   {
    label: "Population (millions)",
    backgroundColor: 
    ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
    data: [2478,5267,734,784,433]
     }
     ]
     };

   var chart = new Chart(piechart,{
   type:"pie",
   data : data1,
   options:{}
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM