3
votes

I've added a Google Visualization pie chart to my page. It's all working great and I didn't have a problem customising it with the predefined options. However, there isn't an option to display the values within the legend instead of percentages, only within the slices themselves or on the hover tooltip.

I'd like to show the values in the legend and the percentages in the slices (the latter I can do through options).

For a bonus point... can I append "MW" on the end of the values i.e. 145WM is outputted rather than just 145.

My current chart's code: http://pastebin.com/4JJdpxKx

I'm sure it's obvious but the data is being brought in dynamically.

4

4 Answers

1
votes

The only way to add the value to the legend is to change the values or formatted values of the label column's data, which will also change the labels in the tooltips.

Appending "MW" to the end of your numbers is easy: just use a NumberFormatter:

// format column 1 as "1,234 MW"
var formatter = new google.visualization.NumberFormat({pattern: '#,### MW'});
formatter.format(data, 1);
19
votes

It's hard to find proper documentation for Google Charts, and my biggest fear is that because it isn't documented it could be taken away any time, but this should do what you want:

chart1.options = {
    .
    .
    .
    pieSliceText: 'value',
    legend: {
        position: 'labeled',
        labeledValueText: 'both',
        textStyle: {
            color: 'blue', 
            fontSize: 14
        }
    }
};

for both the pieSliceText and labeledValueText I have successfully used the options:

 value
 both
 none
 percent

However, I'm not sure about percent because I get the same result if I use any junk word. As for pieSliceText it seems it does not accept the value both. Also, none is not recognized on the labeledValueText.

So, to be sure you'll have to try the different combinations. I personally would have like to have both on the pieSliceText, but getting it on the labeled legend is good enough for me.

It's unfortunate that Google Charts lack consistency in their options, but that might be because they won't want to continue supporting them. It's even more unfortunate that if documentation for these exist, it is nearly impossible to find.

1
votes

you have to create variables and dynamically fetched the data.

var legendValue = 100;
var legendText1= 'legend1' + legendValue;

data.addRows([[legendText1,legendValue],[],[]])
0
votes

Use below setting

legend: { position: 'labeled', labeledValueText: 'none'}

And code below to customize legend text

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

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