Search code examples
rggplot2plotlyggplotly

ggplotly: how to use a special variable with a standard variable in the text aesthetic?


I'm creating an interactive plot and I want the tooltip to show the time (a variable in the dataset) and the count (a variable calculated by ggplot). Using the advice here I can set one or the other, but not both... Here's an example:

library(tidyverse)

data(ChickWeight)

ChickWeight %>%
  ggplot(aes(x = Time,
             text = paste(format(Time), "-", ..count..))) +
  geom_bar()

plotly::ggplotly(tooltip = "text")

This fails with the error object 'Time' not found, but both text = format(Time) and text = ..count.. work individually. How can I include both values in the text aesthetic?


Solution

  • The ..count.. notation has been superseded by after_stat(count), but in either case, this can only be used in a layer employing this statistical transformation, not the global plot aesthetic mapping. The problem is, you can't use the text aesthetic anywhere other than the global aesthetic mapping.

    The obvious way round this is to manipulate the data before plotting, which is just as straightforward as getting ggplot to do it for you:

    library(tidyverse)
    
    data(ChickWeight)
    
    (ChickWeight %>%
      count(Time) %>%
      ggplot(aes(x = Time, text = paste(Time, "-", n))) +
      geom_bar()) %>%
      plotly::ggplotly()
    

    enter image description here