1

I would like to create a plot using plotly::ggplotly(). This works just fine.

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.2.2

p <-
  mtcars |>
  ggplot() +
  geom_histogram(
    aes(
      x = disp,
      text = after_stat(count)
    )
  )
#> Warning in geom_histogram(aes(x = disp, text = after_stat(count))): Ignoring
#> unknown aesthetics: text

plotly::ggplotly(p)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

There is a nice trick with ggplotly() that allows me to use dummy aesthetics to display in the tooltip. Below, I use the text aesthetic for this purpose. However, glue() doesn't work with after_stat(). How can I fix this?

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.2.2

p <-
  mtcars |>
  ggplot() +
  geom_histogram(
    aes(
      x = disp,
      text = glue::glue('{after_stat(count)}')
    )
  )
#> Warning in geom_histogram(aes(x = disp, text =
#> glue::glue("{after_stat(count)}"))): Ignoring unknown aesthetics: text

plotly::ggplotly(p)
#> Error in after_stat(count): object 'count' not found
joshbrows
  • 77
  • 7

1 Answers1

1

It work with text outside aes (that surprises me):

p <-
   ggplot(data = mtcars, aes(x = disp), text = glue::glue('{after_stat({count})}')) +
   geom_histogram()
 
plotly::ggplotly(p)
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
  • It does work, but it doesn't display anything in the tooltip. If I change it to `glue::glue('Bin Size = {after_stat({count})}')`, it doesn't change the tooltip. – joshbrows Jun 02 '23 at 11:58