将数据从数组插入饼图(chart.js)

问题描述 投票:0回答:1

我有两个要插入到饼图中的数据数组。

所以我有这个代码:

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'
      }
    }
});

而不是写标签和数据,我想从2个数组中获得此信息(一个用于标签,另一个用于数据)。我该怎么办?

javascript html chart.js
1个回答
0
投票
请使用为您创建的以下jsfiddle,这可能会对您有所帮助。

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/[email protected]"></script> </body> </html>

js文件中的#代码

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:{} })

© www.soinside.com 2019 - 2024. All rights reserved.