Want to show percentage data in legends of google pie chart

我只是一个虾纸丫 提交于 2019-12-23 12:26:36

问题


I am using google charts API specifically pie chart in my code i want to show percentage which is displayed inside chart to the legends also

How can i display 29.2% sleep in legend?


回答1:


You can do this two ways; either set the formatted values of the labels in the DataTable to include the percents, eg:

// assume sleep is row 4, "sleepPercent" is the percent for sleep
data.setFormattedValue(4, 0, data.getValue(4, 0) + ' (' + (sleepPercent * 100).toFixed(1) + '%)');

or you can set the legend.position option to "labeled", which changes the way the legend is drawn, but adds the percents to the labels:

legend: {
    position: 'labeled'
}

see an example here: http://jsfiddle.net/asgallant/Su6TX/




回答2:


Try this for all values:

var total = 0;
    for (var i = 0; i < data.getNumberOfRows(); i++) {
            total = total + data.getValue(i, 1);    
    }

    for (var i = 0; i < data.getNumberOfRows(); i++) {
            var label = data.getValue(i, 0);
        var val = data.getValue(i, 1) ;
        var percentual = ((val / total) * 100).toFixed(1); 
        data.setFormattedValue(i, 0, label  + '- '+val +' ('+ percentual + '%)');    
    }


来源:https://stackoverflow.com/questions/19178029/want-to-show-percentage-data-in-legends-of-google-pie-chart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!