简体   繁体   English

使用chart.js的带有Json数据的动态饼图

[英]Dynamic Pie Chart With Json Data using chart.js

I am creating a piechart using chart.js. 我正在使用chart.js创建一个饼图。 I have a json data like 我有一个JSON数据像

   [
     {
       "Subcontractor": "C1",
       "Deficiency": 67
     },
     {
       "Subcontractor": "C2",
       "Deficiency": 25
     },
     {
      "Subcontractor": "C3",
      "Deficiency": 12
     }, 
     {
      "Subcontractor": "C5",
      "Deficiency": 7
     },
     {
      "Subcontractor": "C4",
      "Deficiency": 5
     },
     {
      "Subcontractor": "C6",
      "Deficiency": 1
     }
   ]

I want to use the Subcontractor value as the pie chart label and the Deficiency value as the chart value . 我想将Subcontractor值用作饼图标签 ,将Deficiency值用作图表

How to pass this dynamically into the pie chart in chart.js? 如何将其动态传递到chart.js中的饼图中?

Also, when I click on a particular slice I want to reload/refresh the pie chart with different data. 另外,当我单击特定的切片时,我想用不同的数据重新加载/刷新饼图。

You could bind to the click event of the chart, get the active segment of the pie chart and based on that change the information displayed by the chart. 您可以绑定到图表的click事件,获取饼图的活动段,并基于此更改图表显示的信息。

The example below resets the chart when you click on the Red segment, and adds to the charts all entries of an arbitrary dataset data2 下面的示例在单击Red部分时会重置统计图,并将任意数据集data2所有条目添加到统计图

$("#myChart ").click(  
    function (evt) {
        var activePoints = myChart.getSegmentsAtEvent(evt);
        var activeLabel = activePoints[0].label;

        if (activeLabel == "Red") {
            while (myChart.segments.length > 0) {
                myChart.removeData()
            }
            for (i = 0; i < data2.length; i++) {
                myChart.addData(data2[i])
            }
        }
    });
});

Full example here: http://jsfiddle.net/bsxg7jt7/ 此处的完整示例: http : //jsfiddle.net/bsxg7jt7/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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