将动态 json 数组传递给 Highcharts 饼图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8216090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:04:13  来源:igfitidea点击:

To pass dynamic json array to Highcharts Pie Chart

arraysjsonhighcharts

提问by rehan

I passed json encoded string(eg. $TEXT2 consisting ["chrome","15","firefox","20"]) from xcode to an array(eg. arr) in javascript.Now I want to pass this array containing json string dynamically to Highcharts Pie. The HTML code is

我将 json 编码的字符串(例如 $TEXT2 包含 ["chrome","15","firefox","20"]) 从 xcode 传递到 javascript 中的数组(例如 arr)。现在我想传递这个包含json 字符串动态到 Highcharts Pie。HTML代码是

<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=20, user-scalable=no;" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Pie chart</title>

<!-- 1. Add these JavaScript inclusions in the head of your page -->
<script type="text/javascript" src="jquery-1.6.2.js"></script>
<script type="text/javascript" src="highcharts.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script type="text/javascript">

var chart;
var arr = $TEXT2;

$(document).ready(function(){
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Interactive Pie'
},
tooltip: {
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.y +' %';
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: []
}]
});
});
</script>
<body>
<br>
<!-- 3. Add the container -->
<div id="container" style="width: 300px; height: 350px; margin: 0 auto"></div>
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
</body>
</html>

I am trying to use getjson method although m unaware of its usage. Since i want to pass my array i.e arr to data[] in Highcharts,I am doing:

我正在尝试使用 getjson 方法,尽管我不知道它的用法。由于我想将我的数组即 arr 传递给 Highcharts 中的 data[],我正在做:

$.getJSON("arr", function(json) {
chart.series = json;               
var chart = new Highcharts.Chart(chart);
     });

Can anyone help me on dis. Thanks in advance.

任何人都可以帮助我解决问题。提前致谢。

回答by Mark

I would wrap the JSON call in the document.ready function and then wrap the plot call in the getJSON's success callback:

我会将 JSON 调用包装在 document.ready 函数中,然后将 plot 调用包装在 getJSON 的成功回调中:

$(document).ready(function() {

  $.getJSON("arr", function(json) {

    chart = new Highcharts.Chart({
      chart: {
        renderTo: 'container',
        plotBackgroundColor: null,
        plotBorderWidth: null,
        plotShadow: false
      },
      title: {
        text: 'Interactive Pie'
      },
      tooltip: {
        formatter: function() {
          return '<b>'+ this.point.name +'</b>: '+ this.y +' %';
        }
      },
      plotOptions: {
        pie: {
          allowPointSelect: true,
          cursor: 'pointer',
          dataLabels: {
            enabled: false
          },
          showInLegend: true
      },
      series: [{
        type: 'pie',
        name: 'Browser share',
        data: json
      }]
    });
  });
});

Of course for this to work, you should modify your backend code to return a properly formatted array of arrays that HighCharts expects:

当然,要使其正常工作,您应该修改后端代码以返回 HighCharts 期望的格式正确的数组数组:

[["chrome",15],["firefox",20]]

You could "fix" your returned array in the JS, but it would be better to do it in the JSON backend call.

您可以在 JS 中“修复”返回的​​数组,但最好在 JSON 后端调用中进行。

回答by Abhisek Das

<script type="text/javascript">
    jQuery(document).ready(function () {
        alert('call pie');

        var data1 = $("#dataidd").val();
        alert('pie data' + data1);


        /*--------Pie Chart---------*/
        $('#PieChartDiv').highcharts({
            chart: {
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false
            },
            title: {
                text: 'Comparision and Analysis Report'
            },
            tooltip: {
                pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                        style: {
                            color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                        }
                    }
                }
            },
            series: [{
                type: 'pie',
                name: 'Issue Details',
                // data: jQuery.parseJSON(data1)
                data: JSON.parse(data1)

            }]
        });
    });
    </script>

回答by ayhtut

You can bind chart with JSON data, directly. You just need to set the json property names as highchart standard. 'Y' for value and 'name' for label.

您可以直接将图表与 JSON 数据绑定。您只需要将 json 属性名称设置为 highchart 标准。'Y' 表示值,'name' 表示标签。

Your JSON should be as like follow:

您的 JSON 应如下所示:

[ { name: "Chrome", y: 25 }, { name: "Firefox", y: 20 } ]

回答by Xanarus

Simply do :

简单地做:

Create array with Jquery as bellow :

使用 Jquery 创建数组如下:

$.each(data['values'], function(i, val) {
                    x_values_sub['name'] = i
                    x_values_sub['y'] = val
                    x_values.push(x_values_sub);
                    x_values_sub = {};
});

// Then call this array with HighCharts as data

// 然后用 HighCharts 作为数据调用这个数组

series: [{
                            type: 'pie',
                            name: null,
                            data: x_values
}]

// Tested and it works with simple javascript object :

// 经过测试,它适用于简单的 javascript 对象:

Object Part1Name: 25 Part2Name: 75__proto__: Object