2

I have a histogram and I'd like the tooltip to show the percent of observations in that bin.

Here's a simple (reproducible) histogram:

library(tidyverse)
library(ggplot2)
library(plotly)
 
hist <- iris %>%
  ggplot(aes(x = Sepal.Length)) +
  geom_histogram(bins = 20)
 
hist %>%
  ggplotly(
    # This gives hoverover the count and the variable, but I'd like it
    # to also have the percent of total observations contained in that bin
    tooltip=c("count", "Sepal.Length")
  )

 

Along with "count" and "Sepal.Length", I'd like to also show the percent of the total number of observations in the tooltip.  

For example, the left-most bin (which contains 4 observations), should have a value of 2.7% (4/150)

stevec
  • 41,291
  • 27
  • 223
  • 311

1 Answers1

2

I would try using text argument in ggplot and set to the count divided by the sum of all counts. Using sprintf you can get the format desired. In your tooltip reference text.

library(tidyverse)
library(ggplot2)
library(plotly)

hist <- iris %>%
  ggplot(aes(x = Sepal.Length, 
             text = sprintf("Percent: %0.1f", ..count../sum(..count..) * 100))) +
  geom_histogram(bins = 20)

hist %>%
  ggplotly(
    tooltip=c("count", "text", "Sepal.Length")
  )
Ben
  • 28,684
  • 5
  • 23
  • 45