1

I need to have a custom tooltip displayed when a user hovers over a square in a treemap and I use this article as the basis.

The treemap must be built with R and googleVis library using a gvisTreeMap() function. According to the mentioned article, I created a parameter generateTooltip in the list of options of the function and assigned it with a code for creating an anonymous function. Here is a completed code for a gvisTreeMap() invocation:

plot(gvisTreeMap(Data,
    idvar="Name.of.the.Company",
    parentvar="Name.of.the.Parent",
    sizevar="Loan.Size..INR.in.million.",
    options=list(width='*', 
        height=600, 
        minColorValue=0, 
        maxColorValue=0, 
        generateTooltip = "function(row, size, value) { 
                              return '<div style=\"background:#fd9; padding:10px; border-style:solid\">' + 'Some text' + '</div>'; 
                           }"
)))

The resulting JS code in my HTML-page looks like this:

// jsDrawChart
...
var options = {};
options["height"] = 600;
options["minColorValue"] = 0;
options["maxColorValue"] = 0;
options["generateTooltip"] = "function(row, size, value) { return '<div style=\"background:#fd9; padding:10px; border-style:solid\">' + 'Some text' + '</div>'; }";

Here options["generateTooltip"] is initialized with a string which causes an error (while I expected that the string would be automatically recognized as a function definition). So, I'd like to know are there ways to pass the function definition from R environment to the generateTooltip property?

2 Answers 2

4

I know this is a post from over a year ago.. but while I was dealing with the exact same problem today, I couldn't find a specific solution anywhere else, so I thought I would share my solution in hope that someone would find this useful in the future.

I actually used your post, Mstislav, as a starting point, but I ran into the same problem trying to assign the JavaScript function in the options list. After a few unsuccessful attempts to remove the quotation marks (I was able to remove the quotation marks with as.symbol() and unquote(), but got error messages after passing the result into gvisTreeMap), I realized that the crux of the problem is that the Google Charts documentation assumes that you are writing the code directly in JavaScript, while you are actually feeding arguments into R functions which then translates them into JavaScript.

Since there seems to be no easy way to pass the JavaScript function into the gvisTreeMap function call, I thought I'd try identifying where in the googleVis source code that option list gets translated into JavaScript, and then modifying the Javascript directly according to the article.

After downloading the googleVis source code and tracing back from the gvisTreeMap function (in gvisTreeMap.R), I found the snippet of code I needed to modify in gvis.R:

jsDrawChart <- '
// jsDrawChart

// ** begin modified portion **//
function showFullTooltip(row, size, value) {
return \'<div style="background:#fd9; padding:10px; border-style:solid">\' +
\'Group: \' + row + \'<br>\' +
\'Headcount: \' + size + \'<br>\' +
\'Turnover Rate: \' + value + \' </div>\';
}
// ** end modified portion **//

function drawChart%s() {
var data = gvisData%s();
var options = {};
%s
// ** begin modified portion **//
options["generateTooltip"] = showFullTooltip;
// ** end modified portion **//
%s
%s
%s
}
%s  
'
jsDrawChart <- sprintf(jsDrawChart, chartid,  chartid,
                       paste(gvisOptions(options), collapse="\n"),
                       jsFormats,
                       gvisNewChart(chartid,type,options),
                       gvisListener(chartid, type, options),
                       gvisEditor(chartid,type,options)
)

There are two portions I modifed (wrapped in //** begin/end modified portion **//). The first part defines the showFullTooltip function, and the second part adds the generateTooltip option to the options list. This worked like a charm for me. The Google Charts article was very helpful in describing how to modify the JavaScript code. The trick is simply figuring out WHERE to find that piece of code in the googleVis programs.

To run this code, I found that you don't have to "override" the googleVis package. You just have to save a copy of the modified gvis.R and unmodified gvisTreeMap.R in your project folder (or anywhere accessible to you). Then, at the top of your program, load the googleVis library (so you have all the dependencies), then source your versions of gvis.R, and gvisTreeMap.R (in that order). The modified versions of the googleVis functions will then override the ones you've loaded from the googleVis library.

0

I had the same problem and xxk's answer got me part of the way there, except in my case, I wanted to combine both the default tooltips (with just the name of the rectangle - super useful to include when you have some tiny areas in the plot), with the extra details from showFullTooltip (i.e., value and size). For this to be possible, you need to (largely) follow the same steps suggested by xxk, i.e.,

  • downloading the googleVis source code
  • extracting and saving both gvis.R and gvisTreeMap.R somewhere sensible
  • editing only gvis.R (1), and saving it
  • loading any other R packages you may require, including googleVis (2)
  • only then sourcing your custom gvis.R and gvisTreeMap.R into your main script (in that order).

Now, a few deviations are necessary from the approach above, which I've marked between brakets:

(1) Within gvis.R, you need to be careful where you place function showFullTooltip, due to some scoping problems. A better place is within the declaration for gvisNewChart. Once edited, it would look like below. Notice also row from xxk's solution was replaced by data.getValue(row, 0), aka the label of the rectangle:

gvisNewChart <- function(chartid,type,options){

  ret <- ""
  if(is.null(options$gvis$gvis.editor)){
    jsnewchart <- "
    var chart = new google.visualization.%s(
    document.getElementById(\'%s\')
    );

    // ** begin modified portion **//
    function showFullTooltip(row, size, value) {
    return \'<div style=\"background:#fd9; padding:10px; border-style:solid\">\' +
    \'Name: \' + data.getValue(row, 0) + \'<br>\' +
    \'Average: \' + size + \'<br>\' +
    \'Normalised: \' + value + \' </div>\';
    }
    // ** end modified portion **//

    chart.draw(data,options);"
    ret <- sprintf(jsnewchart,type,chartid)  

  } else {
    jsnewchart <- "
    chart%s = new google.visualization.ChartWrapper({
    dataTable: data,       
    chartType: '%s',
    containerId: '%s',
    options: options
    });
    chart%s.draw();
    "
    ret <- sprintf(jsnewchart,chartid,type,chartid,chartid)
  }
  ret
  } 

(2) I also needed to load library(jsonlite) in my main R script for all this to work.


And another thing. You do not need to do anything in particular in your R call to gvisTreeMap(). The tooltips will now behave in the intended way 'by default'. For instance, now:

gvisTreeMap( nested_data, idvar = "Child", parentvar = "Parent",
             sizevar = "Value", colorvar = "Value",
             options = list(
               minColorValue = 0, 
               maxColorValue = 100,
               minColor = 'green',
               midColor = '#fff',
               maxColor = 'red',
               showScale = TRUE,
               maxDepth = 2,
               width = "100%", height = 800             
             )

should just produce detailed tooltips on its own, without specifying this behaviour.

I was lucky enough to have great people around to help me with this, as I couldn't manage myself. So thanks @DavidFarrell and @RossAnderson.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.