使用Chart.JS显示饼图

时间:2017-04-28 08:48:21

标签: javascript chart.js2

我已成功显示和操作条形图,但我无法弄清楚如何处理饼图。当我使用检查工具时,我可以看到有些东西存在。我使用以下代码: Chart.js CDN:

图表的Canvas容器: 从文档中获取的Javascript:

var ctx = document.getElementById("myChart");       
var myChart = new Chart(ctx,{
    type:"pie",
    data: [3, 4],
    options: {
        animation:{
            animateScale:true
        }
    }
});

艾米建议将受到欢迎。

2 个答案:

答案 0 :(得分:0)

根据文档(Chart.js - Pie & Doughnut Charts),data变量应具有以下结构:

data: {
    labels: ["Green", "Blue", "Gray", "Purple", "Yellow", "Red", "Black"],
    datasets: [{
    backgroundColor: [ /* backgroundColor is optional */
        "#2ecc71",
        "#3498db",
        "#95a5a6",
        "#9b59b6",
        "#f1c40f",
        "#e74c3c",
        "#34495e"
    ], 
    data: [12, 19, 3, 17, 28, 24, 7]
}]

}

正如我所看到的,这就是你的问题。

答案 1 :(得分:0)

试试这个。有关详情,请参阅Pie chart Usage。评论是否有任何混淆

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
  type: 'pie',
  data: {
    labels: ["Green", "Blue", "Gray", "Purple", "Yellow", "Red", "Black"],
    datasets: [{
      backgroundColor: [
        "#2ecc71",
        "#3498db",
        "#95a5a6",
        "#9b59b6",
        "#f1c40f",
        "#e74c3c",
        "#34495e"
      ],
      data: [12, 19, 3, 17, 28, 24, 7]
    }]
  }
});
.container {
  width: 80%;
  margin: 15px auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script>
<div class="container">
  <h2>Chart.js — Pie Chart Demo</h2>
  <div>
    <canvas id="myChart"></canvas>
  </div>
</div>