Search code examples
chartsgoogle-visualization

How to show a tooltip with info from several data points that have the same x and y on google charts


So basically I have data that looks like

['x', 'y', 'name']

that I am showing on a Scatter Chart.

I want the name to appear in the tooltip when hovering the data point, so what I did is have something like

data.addColumn('number', 'x');
data.addColumn('number', 'y');
data.addColumn({type: 'string', role: 'tooltip'});

and then

data.addRows([x, y, name])

My issue is that it is possible that my data has several entries have the same x and y. And when that happens, a single data point is shown on the graph with the tooltip of the last name in the rows. I would like it to be a concatenation of the several names.

Any way to tweak the options to achieve this? Or am I doomed to build my own logic to handle it? Cheers


Solution

  • try the following option...

    aggregationTarget: 'category'
    

    aggregationTarget - 'category': Group selected data by x-value.


    EDIT

    another option is to use a data view with a calculated column for the tooltip role.

    the calculated column has a calc function that runs for every row.
    here, find the x, y values for the current row,
    then check the data table for other rows with matching x, y values,
    and concatenate the names.

    see following snippet...

    // create data table
    var data = new google.visualization.DataTable();
    data.addColumn('number', 'x');
    data.addColumn('number', 'y');
    data.addColumn({type: 'string', role: 'tooltip'});
    
    // add rows
    data.addRows([[x, y, name]]);
    
    // create data view
    var view = new google.visualization.DataView(data);
    
    // set columns on data view
    view.setColumns([0, 1, {
      calc: function (dt, row) {
        // get x, y for current row
        var x = dt.getValue(row, 0);
        var y = dt.getValue(row, 1);
        var name = '';
    
        // find rows with matching x, y
        for (var i = 0; i < dt.getNumberOfRows(); i++) {
          var testX = dt.getValue(i, 0);
          var testY = dt.getValue(i, 1);
          if ((x === testX) && (y === testY)) {
            // concat name
            if (name !== '') {
              name += ', ';
            }
            name += dt.getValue(i, 2);
          }
        }
    
        return name;
      },
      role: 'tooltip',
      type: 'string'
    }]);
    
    // draw chart with view
    chart.draw(view, options);