Need Tooltips: Change google sheet existing data i

2019-07-20 01:58发布

问题:

Problem: All the documentation I see uses a DataTable that writes the data in the script itself. I need to call this tooltip data from existing rows. I need to understand the code difference between an HTML page and an embedded chart in a google sheet.

Goal: I have a scatter plot that needs custom tooltips. I need the data from column Q to show as the tooltip, on hover with the data in column R and S insert chart using this code plus tooltip:

    function newChart() {
  // Generate a chart representing the data in the range of A1:B15.
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[11];

  var chart = sheet.newChart()
     .setChartType(Charts.ChartType.SCATTER)
     .addRange(sheet.getRange('R3:S5000'))
     .addRange(sheet.getRange('Q3:Q5000'))

     .setPosition(5, 5, 0, 0)
     .build();

  sheet.insertChart(chart);
}

-OR-

 function drawChart() {
        var dataTable = new google.visualization.DataTable();
        dataTable.addColumn('string', 'Year');
        dataTable.addColumn('number', 'Sales');
        // A column for custom tooltip content
        dataTable.addColumn({type: 'string', role: 'tooltip'});
        dataTable.addRows([
          ['2010', 600,'$600K in our first year!'],
          ['2011', 1500, 'Sunspot activity made this our best year ever!'],
          ['2012', 800, '$800K in 2012.'],
          ['2013', 1000, '$1M in sales last year.']
        ]);

        var options = {
          tooltip: {isHtml: true},
          legend: 'none'
        };
        var chart = new google.visualization.ColumnChart(document.getElementById('col_chart_html_tooltip'));
        chart.draw(dataTable, options);
      }

references: https://developers.google.com/chart/interactive/docs/reference#DataView https://developers.google.com/chart/interactive/docs/customizing_tooltip_content#tooltip-actions https://developers.google.com/chart/interactive/docs/spreadsheets

回答1:

in the embedded chart, use a data view definition to add the tooltip role...

see following snippet...

function newChart() {
  // Generate a chart representing the data in the range of A1:B15.
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[11];

  // build the data view definition
  var COLUMN_SPEC = [
    0,
    1,
    {sourceColumn: 2, role: 'tooltip'}
  ];
  var viewSpec = Charts.newDataViewDefinition()
     .setColumns(COLUMN_SPEC)
     .build();

  var chart = sheet.newChart()
     .setChartType(Charts.ChartType.SCATTER)
     .setDataViewDefinition(viewSpec)
     .addRange(sheet.getRange('R3:S5000'))
     .addRange(sheet.getRange('Q3:Q5000'))

     .setPosition(5, 5, 0, 0)
     .build();

  sheet.insertChart(chart);
}