Search code examples
javascripthtmlchartsgoogle-visualizationtooltip

Google chart : modify toopl tip


I have a joint chart using google chart API. Here i want to update the tool tip of the chart.

As there is a lot of overlap in these charts i might not be able to actually hover over each discrete point and see data.


Solution

  • you can use a DataView to provide a calculated column
    which builds the tooltip for that row

    see following snippet...

    var dataView = new google.visualization.DataView(joinedData);
    dataView.setColumns([0, 1, {
      calc: function (dt, row) {
        return getTooltip(dt, row);
      },
      role: 'tooltip',
      type: 'string',
      p: {
        html: true
      }
    }, 2, {
      calc: function (dt, row) {
        return getTooltip(dt, row);
      },
      role: 'tooltip',
      type: 'string',
      p: {
        html: true
      }
    }]);
    
    function getTooltip(dt, row) {
      var tooltip = '<div class="tooltip">';
      tooltip += '<div>' + dt.getFormattedValue(row, 0) + '</div>';
    
      tooltip += '<div>' + dt.getColumnLabel(1) + '</div>';
      if (dt.getValue(row, 1) === null) {
        tooltip += '<div>' + dt.getFormattedValue(row + 1, 1) + '</div>';
      } else {
        tooltip += '<div>' + dt.getFormattedValue(row, 1) + '</div>';
      }
    
      tooltip += '<div>' + dt.getColumnLabel(2) + '</div>';
      if (dt.getValue(row, 2) === null) {
        if (row > 0) {
          tooltip += '<div>' + dt.getFormattedValue(row - 1, 2) + '</div>';
        }
      } else {
        tooltip += '<div>' + dt.getFormattedValue(row, 2) + '</div>';
      }
    
      tooltip += '</div>';
      return tooltip;
    }
    

    full snippet --> http://jsfiddle.net/sqdfrf8f/1/


    note: there is some sort of bug,
    in that the chart will not respect column properties on data views
    so the html property doesn't get set
    the work around is to use data view method --> toDataTable()

    also: need to use updated library for google charts, see --> update library loader code