在amcharts中显示条形图上的百分比

时间:2016-12-08 00:36:03

标签: javascript amcharts

我是Amcharts的新手,我试图在列图中显示数据的百分比。

var amc=AmCharts.makeChart("pickup_bar",
        {
    "type": "serial",
    "dataLoader": {
        "url": "the data url"
      },
    "categoryField": "distance",
    "startDuration": 1,
    "categoryAxis": {
        "gridPosition": "start"
    },
    "trendLines": [],
    "graphs": [
        {
        "valueField": "taxi",
        "fillColors":"#1E90FF",
        "type": "column",
        "balloonText": "[[title]] of [[category]]:[[value]]",
        "fillAlphas": 0.8,
        "lineAlpha": 0.2,
        "id": "AmGraph-1",
        "title": "Distance Traveled",

        "labelText": " ",
        "labelPosition": "inside",

        "labelFunction": function( item ) {
            var total = 0;
            for ( var i = 0; i < chart.dataLoader.length; i++ ) {
              total += chart.dataLoader[ i ][ item.graph.valueField ];
            }

            var percent = Math.round( ( item.values.value / total ) * 1000 ) / 10;
            return percent + "%";
          }
    }],
"guides": [],
"valueAxes": [
    {
        "id": "ValueAxis-1",
        "title": "Milage",
        "gridColor": "#FFFFFF",
        "gridAlpha": 0.2
    }
],
"categoryAxis": {
    "title": "(in Kilometers)"
  },
"gridAboveGraphs": true,
"allLabels": [],
"balloon": {},
"legend": {
    "enabled": true,
    "useGraphSettings": true
},
"titles": [
    {
        "id": "Title-1",
        "size": 15,
        "text": "Taxis Driving Distance "
    }
]
});

数据格式为json,将为

> [{"distance":"<50","taxi":309,"day":1},{"distance":"50-100","taxi":100,"day":1},{"distance":"100-200","taxi":300,"day":1},...]

图表加载甚至加载但是当我删除行

"labelPosition": "inside",

图表出现但不是百分比。

任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您的代码中存在一些问题。

首先,您正在访问未定义的chart变量。您的代码将图表对象分配给amc。您需要更改代码以匹配,或通过item.graph.chart访问图表实例。

其次,您循环遍历labelFunction中的dataLoader而不是dataProvider。 dataLoader对象不存储您的图表数据,它只是在从指定的URL检索数据后将数据加载到图表的dataLoader中。这是你的固定labelFunction:

    "labelFunction": function(item) { 
      var total = 0;
      var chart = item.graph.chart;
      for (var i = 0; i < chart.dataProvider.length; i++) {
        total += chart.dataProvider[i][item.graph.valueField];
      }

      var percent = Math.round((item.values.value / total) * 1000) / 10;
      return percent + "%";
    } 

在进行这些更改后,标签会显示我的数据。如果您还没有看到标签,也许您在有限的空间内拥有大量数据。默认情况下,如果图表值标签不适合,图表将不会呈现图表值标签。如果要覆盖此行为,请将图形的showAllValueLabels属性设置为true。

Demo