【问题标题】:How to use json data as highcharts Pie Chart?如何使用 json 数据作为 highcharts 饼图?
【发布时间】:2016-12-10 08:14:43
【问题描述】:

我创建了一个 ajax 请求,它返回这样的数据

Object
negative:3
neutral:3
positive:94

这是直接来自console.log();

我正在尝试使用此数据创建一个饼图,但是当我尝试它时它不会绘制图表,并且除了积分之外什么都没有显示,并且控制台中也没有错误。但是如果我手动输入这样的数据:

series: [{
            name: 'Brands',
            data: [

                { name: 'Positive', y: 94 },
                { name: 'Negative', y: 3 },
                { name: 'Neutral', y: 3 },
            ]
        }]

没问题。

我的代码是:

function pieChart(data) {
    // Make monochrome colors and set them as default for all pies
    Highcharts.getOptions().plotOptions.pie.colors = (function () {
        var colors = [],
            base = Highcharts.getOptions().colors[0],
            i;

        for (i = 0; i < 10; i += 1) {
            // Start out with a darkened base color (negative brighten), and end
            // up with a much brighter color
            colors.push(Highcharts.Color(base).brighten((i - 3) / 7).get());
        }
        return colors;
    }());

    // Build the chart
    Highcharts.chart('pieChart', {
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie'
        },
        title: {
            text: 'Browser market shares at a specific website, 2014'
        },
        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: [{
            name: 'Brands',
            data: data
        }]
    }); 
};

【问题讨论】:

  • 你的 json 看起来怎么样?您需要从服务器返回 json,或者在客户端创建它。
  • 谢谢,服务器正在返回响应。 console.log()返回的数据输出Object {positive: 94, negative: 3, neutral: 3}

标签: javascript jquery json charts highcharts


【解决方案1】:

您使用ajax 请求从服务器收到的响应是一个对象。

您只需根据收到的响应创建一个json 数组。

var object={'positive':94,'neutral':2,'negative':2};
var data=[];
for(i in object){
    data.push({"name":i,"y":object[i]});
}

并将其设置为highchart 系列。

series: [{
        name: 'Brands',
        data: data
}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多