How to Change Tooltip Text for Google Chart API

Google chart API styling tooltips

I found a solution through serendipity:

<style>
path {
fill: yellow;
}
</style>

Anyway, I did not find any configuration option for background in the google charts API.

Google Charts - How to append text to default tooltip

it's not possible to add content to the default tooltip via standard functionality

to do so requires manipulating the tooltip directly when it is shown

the following working snippet listens for the 'onmouseover' event on the chart

then modifies the tooltip (if found)

using the row # passed as a property of the event argument

keep in mind, the style (font-size) will change according to the size of the chart

the snippet copies the style from the existing lines

google.charts.load('current', {  callback: function () {    var dataTable = new google.visualization.DataTable({      cols: [        {label: 'Element', type: 'string'},        {label: 'Duration', type: 'number'},        {role: 'style', type: 'string'}      ],      rows: [        {c:[{v: 'Amazon Elastic Transcoder'}, {v: 3116, f: '3,116 s'}, {v: 'orange'}]},        {c:[{v: 'Amazon Elastic Transcoder'}, {v: 8523, f: '8,523 s'}, {v: 'cyan'}]}      ]    });
var options = { backgroundColor: 'transparent', legend: 'none', theme: 'maximized', hAxis: { textPosition: 'none' }, tooltip: { isHtml: true } };
var container = document.getElementById('chart_div'); var chart = new google.visualization.ColumnChart(container);
google.visualization.events.addListener(chart, 'onmouseover', function (props) { var duration = dataTable.getValue(props.row, 1); var hours = parseInt( duration / 3600 ) % 24; var minutes = parseInt( duration / 60 ) % 60; var seconds = duration % 60;
var tooltip = container.getElementsByTagName('ul'); var tooltipLabel = container.getElementsByTagName('span'); if (tooltip.length > 0) { // increase tooltip height tooltip[0].parentNode.style.height = '95px';
// add new li element var newLine = tooltip[0].appendChild(document.createElement('li')); newLine.className = 'google-visualization-tooltip-item';
// add span for label var lineLabel = newLine.appendChild(document.createElement('span')); lineLabel.style.fontFamily = tooltipLabel[0].style.fontFamily; lineLabel.style.fontSize = tooltipLabel[0].style.fontSize; lineLabel.style.color = tooltipLabel[0].style.color; lineLabel.style.margin = tooltipLabel[0].style.margin; lineLabel.style.textDecoration = tooltipLabel[0].style.textDecoration; lineLabel.innerHTML = dataTable.getColumnLabel(1) + ': ';
// add span for value var lineValue = newLine.appendChild(document.createElement('span')); lineValue.style.fontFamily = tooltipLabel[0].style.fontFamily; lineValue.style.fontSize = tooltipLabel[0].style.fontSize; lineValue.style.fontWeight = tooltipLabel[0].style.fontWeight; lineValue.style.color = tooltipLabel[0].style.color; lineValue.style.margin = tooltipLabel[0].style.margin; lineValue.style.textDecoration = tooltipLabel[0].style.textDecoration; lineValue.innerHTML = hours + 'h ' + minutes + 'm ' + seconds + 's'; } });
chart.draw(dataTable, options); }, packages:['corechart']});
<script src="https://www.gstatic.com/charts/loader.js"></script><div id="chart_div"></div>

Can I customize the tooltip text in a Google Geochart chart?

It seems like it is impossible to format the text the exact way I was attempting to with the GeoChart tool. Below is the solution I finally came up with and the rendered map:

Rendered Map with Tooltip View

Sample Image

PHP & JavaScript Code

<!-- generate geo map -->
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>

google.load( 'visualization', '1', { 'packages': ['geochart'] } );
google.setOnLoadCallback( drawRegionsMap );

function drawRegionsMap()
{

// create data table
var data = google.visualization.arrayToDataTable([
<?php echo $data_table; ?>
]);

// create chart object
var chart = new google.visualization.GeoChart(
document.getElementById( 'chart_div' )
);

// defines the data for the tooltip
var formatter = new google.visualization.PatternFormat('{0}');
formatter.format( data, [0,1], 1 );
var formatter = new google.visualization.PatternFormat('{2}');
formatter.format( data, [0,1,2], 0 );

// defines the data for the chart values
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);

// set options for this chart
var options =
{
width: <?php echo $width; ?>,
region: 'US',
resolution: 'provinces',
colorAxis: { colors: ['#abdfab', '#006600'] },
legend: 'none'
};

// draw chart
chart.draw( view, options );

};

</script>

<div id="chart_div" style="width: <?php echo $width; ?>px; height: <?php echo $height; ?>px;"></div>

Rendered HTML

<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>

google.load( 'visualization', '1', { 'packages': ['geochart'] } );
google.setOnLoadCallback( drawRegionsMap );

function drawRegionsMap()
{

// create data table
var data = google.visualization.arrayToDataTable([
[ 'State', 'in', 'String' ],
[ 'Arizona', 2, 'Has Facility, Sells Direct' ],
[ 'California', 4, 'Has Facility, Has Distributor, Sells Direct' ],
[ 'Colorado', 1, 'Sells Direct' ],
[ 'Florida', 1, 'Has Distributor' ],
[ 'Georgia', 1, 'Has Distributor' ],
[ 'Idaho', 1, 'Sells Direct' ],
[ 'Illinois', 1, 'Has Distributor' ],
[ 'Indiana', 1, 'Has Distributor' ],
[ 'Iowa', 1, 'Has Distributor' ],
[ 'Kansas', 1, 'Has Distributor' ],
[ 'Kentucky', 1, 'Has Distributor' ],
[ 'Louisiana', 1, 'Has Distributor' ],
[ 'Maryland', 2, 'Has Distributor' ],
[ 'Montana', 1, 'Sells Direct' ],
[ 'Nevada', 2, 'Has Facility, Sells Direct' ],
[ 'New Mexico', 2, 'Has Facility, Sells Direct' ],
[ 'North Carolina', 1, 'Has Distributor' ],
[ 'North Dakota', 1, 'Has Distributor' ],
[ 'Oklahoma', 1, 'Sells Direct' ],
[ 'Oregon', 1, 'Sells Direct' ],
[ 'Pennsylvania', 1, 'Has Distributor' ],
[ 'South Carolina', 1, 'Has Distributor' ],
[ 'Tennessee', 1, 'Has Distributor' ],
[ 'Texas', 1, 'Has Distributor' ],
[ 'Utah', 2, 'Has Facility, Sells Direct' ],
[ 'Washington', 1, 'Sells Direct' ],
[ 'Wyoming', 1, 'Sells Direct' ], ]);

// create chart object
var chart = new google.visualization.GeoChart(
document.getElementById( 'chart_div' )
);

// defines the data for the tooltip
var formatter = new google.visualization.PatternFormat('{0}');
formatter.format( data, [0,1], 1 );
var formatter = new google.visualization.PatternFormat('{2}');
formatter.format( data, [0,1,2], 0 );

// defines the data for the chart values
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);

// set options for this chart
var options =
{
width: 286,
region: 'US',
resolution: 'provinces',
colorAxis: { colors: ['#abdfab', '#006600'] },
legend: 'none'
};

// draw chart
chart.draw( view, options );

};

</script>

<div id="chart_div" style="width: 286px; height: 180px;"></div>

How to change properties of tooltip text?

you can use html tooltips, then use a css class to style them

set the following option...

    tooltip: {
isHtml: true
}

and column property --> p: {html: true}

dataTable.addColumn({ type: 'string', role:'tooltip', p: {html: true}});

see following working snippet...

google.charts.load('current', {  packages: ['calendar']}).then(function () {  var dataTable = new google.visualization.DataTable();  dataTable.addColumn('date' , 'date');   dataTable.addColumn('number', 'num');  dataTable.addColumn({ type: 'string', role:'tooltip', p: {html: true}});  dataTable.addRows([    [ new Date(2017, 11, 20), 150,'<div class="tooltip">Hello</div>'],    [ new Date(2017, 11, 21), 130,'<div class="tooltip">Hello</div>']  ]);
var chart = new google.visualization.Calendar(document.getElementById('tooltip_action'));
var options = { title: "Calendar Chart", colors: ['#e0440e'], height: 350, tooltip: { isHtml: true } };
chart.draw(dataTable, options);});
body {  overflow: auto;}
#tooltip_action { width: 1000px;}
.tooltip { font-size: 24px; padding: 12px;}
<script src="https://www.gstatic.com/charts/loader.js"></script><div id="tooltip_action"></div>

Add custom text to Google Visualization tooltip

Have a look at https://developers.google.com/chart/interactive/docs/roles#whatrolesavailable:

Additional tooltip rows are what you are looking for!

The example:


label: 'Year', 'Sales', null, 'Expenses', null
role: domain, data, tooltip, data, tooltip
'2004', 1000, '1M$ sales, 400, '$0.4M expenses
in 2004' in 2004'
'2005', 1170, '1.17M$ sales, 460, '$0.46M expenses
in 2005' in 2005'
'2006', 660, '.66$ sales, 1120, '$1.12M expenses
in 2006' in 2006'
'2007', 1030, '1.03M$ sales, 540, '$0.54M expenses
in 2007' in 2007'

Google Charts - custom tooltip value for Pie Chart

provide the formatted value in the last argument of setCell

the tooltip will show the formatted value by default

see following working snippet...

google.charts.load('current', {  callback: function () {    drawChart([{name: 'Test1', size: 1234}, {name: 'Test2', size: 324563425}, {name: 'Test3', size: 321453452345}, {name: 'Test4', size: 789078}], 'chart_div');  },  packages: ['corechart']});
var drawChart = function(entries, elementId) { var options = { width: "100%", height: 148, fontSize: 8, tooltip: { textStyle: { bold: true, color: '#000000', fontSize: 13 }, showColorCode: true, isHtml: true, ignoreBounds: true, text: 'both', trigger: 'selection' }, legend: { position: 'right', textStyle: { fontSize: 10 } }, chartArea: { left: 5, top: 10, right: 5, bottom: 10, height: "148", width: "100%" }, sliceVisibilityThreshold: 0, pieSliceText: 'none', //pieHole: 0.4, };
var chart = new google.visualization.PieChart(document.getElementById(elementId));
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name'); data.addColumn('number', 'Size');
data.addRows(entries.length); var i = 0; $.each(entries, function () {
data.setCell(i, 0, this.name); data.setCell(i, 1, this.size, formatBytes(this.size, 1));
i++; });
chart.draw(data, options);}
var formatBytes = function(bytes, precision) { if (isNaN(parseFloat(bytes)) || !isFinite(bytes)) return '-'; if (typeof precision === 'undefined') precision = 1; var units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'], number = Math.floor(Math.log(bytes) / Math.log(1024)); return (bytes / Math.pow(1024, Math.floor(number))).toFixed(precision) + ' ' + units[number];};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://www.gstatic.com/charts/loader.js"></script><div id="chart_div"></div>


Related Topics



Leave a reply



Submit