Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set tooltips to display percentages to match axis in Google Visualization Line Chart?

The tooltips can be set to display percentages using the following code:

var formatter = new google.visualization.NumberFormat({
      fractionDigits: 2,
      suffix: '%'
    });
formatter.format(data, 1); // Apply formatter to first column.

Is there a way for NumberFormat to multiply each element by 100? Otherwise the tooltip appears as .50%.

I am using vAxis.format = "format:'#%' " which does multiply by 100. So .5 is displayed as 50% on the vertical axis.

According to the documentation(icu-project.org/apiref), this can be overwritten by enclosing the % in single quotes, but this did not work.

The net result is that the tooltips do not match the axis. What is the best way to do this?

like image 355
B Seven Avatar asked Jul 17 '11 14:07

B Seven


People also ask

How do you add percentages to a Google chart?

var options = { title: 'Chart Title', vAxis: { minValue: 0, maxValue: 100, format: '#\'%\'' } }; Try escaping the % sign. I've used this to just append the % sign in the y axis.

What is tooltip in chart?

Overview. Tooltips are the labels that appear when users hover over data points on your chart. They generally appear across all ZingChart charts by default, and can display any combination of data values, text, and/or tokens.


1 Answers

I got this working by specifying a formatter exactly as you do:

var chartData = google.visualization.arrayToDataTable(tableData);
var formatter = new google.visualization.NumberFormat({
    fractionDigits: 2,
    suffix: '%'
});
formatter.format(chartData, 1);

The 1 in the last call means the second column, in which I have float values.

Then I specify a format for the axis in the chart options, escaping the percentage sign as pointed out by documentation and others here:

var chartOptions = {
    vAxis: { format: '#\'%\'' }
};

I then draw the chart:

var chart = new google.visualization.ColumnChart(document.getElementById('chart'));
chart.draw(chartData, chartOptions);

This renders a left side axis with values like 10%, 20% and so on. And the tooltips looks like the default one but with a percentage like 10.10%, 20.20% and so on.

If you want two fraction digits in the left side axis as well, use this as format in the chart options instead:

vAxis: { format: '#.00\'%\'' }
like image 50
Markus Amalthea Magnuson Avatar answered Sep 18 '22 11:09

Markus Amalthea Magnuson