9

I've been trying to get a custom tooltip for a stacked bar chart.

var data = new google.visualization.DataTable();
data.addColumn('string', 'Units');
data.addColumn('number', '1');
data.addColumn('number', '2');
data.addColumn('number', '3');
data.addColumn('number', '4');

_1 = 0.123
_2 = 0.23
_3 = 0.3
_4 = 0

data.addRow([_units, _1, _2, _3, _4,]);

var options = {
        isStacked: true,
        height: 150,
        chartArea: { height: 50 },
        legend: { position: 'top' },
};

bchart = new google.visualization.BarChart(bcontainer);
bchart.draw(data, options);

My question then is how to create a tooltip for each: _1, _2, _3, _4?

Thanks

1 Answer 1

16

This is covered in the Google Documentation under DataTable Roles

In the Bar Chart documentation, it explains which roles are available for that chart here

What you need to do is add additional columns to your data with the {role: tooltip} added, with that column showing what you want the tooltip to say.

For instance:

  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Year');
  data.addColumn('number', 'Sales');
  data.addColumn({type: 'string', role: 'tooltip'});
  data.addColumn('number', 'Expenses');
  data.addColumn({type: 'string', role: 'tooltip'});
  data.addRows([
    ['2004', 1000, '1M$ sales in 2004', 400,  '$0.4M expenses in 2004'],
    ['2005', 1170, '1.17M$ sales in 2005', 460, '$0.46M expenses in 2005'],
    ['2006', 660,  '.66$ sales in 2006', 1120, '$1.12M expenses in 2006'],
    ['2007', 1030, '1.03M$ sales in 2007', 540, '$0.54M expenses in 2007']
  ]);

The final code will look like this:

function drawVisualization() {
  // Create and populate the data table.
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Year');
  data.addColumn('number', 'Sales');
  data.addColumn({type: 'string', role: 'tooltip'});
  data.addColumn('number', 'Expenses');
  data.addColumn({type: 'string', role: 'tooltip'});
  data.addRows([
    ['2004', 1000, '1M$ sales in 2004', 400,  '$0.4M expenses in 2004'],
    ['2005', 1170, '1.17M$ sales in 2005', 460, '$0.46M expenses in 2005'],
    ['2006', 660,  '.66$ sales in 2006', 1120, '$1.12M expenses in 2006'],
    ['2007', 1030, '1.03M$ sales in 2007', 540, '$0.54M expenses in 2007']
  ]);

  // Create and draw the visualization.
  new google.visualization.BarChart(document.getElementById('visualization')).
      draw(data,
           {title:"Yearly Coffee Consumption by Country",
            isStacked: true,
            width:600, height:400,
            vAxis: {title: "Year"},
            hAxis: {title: "Sales"}}
      );
}

See an example here.

1
  • I spent hours on this yesterday trying to figure this out. Thank you very much.
    – user290043
    Commented Jan 11, 2013 at 14:45