Frage

I would like to create a tooltip on a ggvis histogram that would show the identification of the elements in that bin. An example:

id <- gl(100, 1)
value <- rnorm(100)
df <- data.frame(id, value)
df %>% ggvis(~value) %>% layer_histograms

I would like a hover tooltip that would give the id of the values included in that bin, but i don't know how to get ggvis to give me this data to use in add_tooltip.

Thanks!

Update:

When using the tooltipFunc from r2evans bellow on a integer variable with cases for most integers, it would give ids duplicated on adjacent bin tooltips. To correct, just changed the inequality sign to reference left closed intervals (default in ggvis).

tooltipFunc <- function(index, value) {
  function(x) {
    if (is.null(x)) return(NULL)
    else {
        paste(index[ (value >= x$xmin_ ) & (value < x$xmax_) ],
                  collapse=', ')
     }
  }
}
War es hilfreich?

Lösung

I saw this feature demonstrated in RStudio's webinar this morning. Thanks for asking, I was meaning to learn about it anyway. The following is a bit of a hack, my first attempt at it, but it shows the ease and power of it:

tooltipFunc <- function(index, value) {
    function(x) {
        if (is.null(x)) return(NULL)
        else {
            strwrap(
                paste(index[ (value >= x$xmin_ ) & (value <= x$xmax_) ],
                      collapse=', '),
                width = 30)
        }
    }
}

df <- data.frame(id=gl(100,1), value=rnorm(100))
df %>%
    ggvis(~value) %>%
    layer_histograms() %>% 
    add_tooltip(tooltipFunc(df$id, df$value), 'hover')

This shows all $ids that are encompassed within a bin. In this case, the x (passed to the function) is a data.frame with one row and four columns: $xmin_, $xmax_, $stack_upr_, and $stack_lwr_. Because the function returns potentially literal HTML, it's not hard to take some liberties with this.

(This could have been done with a simpler function that presumed the presence of the df data.frame, but I thought it was slightly more extensible in this current form for future data sets.)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top