0

When I use ggplotly() to transform a ggplot histogram into a dynamic plot, the hover bring, I assume, the middle point of the interval. This is not intuitive for my public. I need it to display the interval. Ex: [x, y) or something like that. How can i do this?

Here an simple example with the Iris Data Set.

library(tidyverse)
library(plotly)

iris %>% 
  ggplot(
    aes(
      x = Sepal.Length
    )
  ) +
  geom_histogram() -> p 


ggplotly(p)
  

Maybe other thing: when I am creating a ggplot2 histogram, I know I can control the number of bins and the size of bins. Is there a way to have even more control, maybe setting everything in manual?

Thanks in advance and sorry for the bad English!

1 Answers1

0

you can try to calculate the binwidth bw beforehand. I borrowed for that the solution here. Then calculate the breaks hist_breaks and add the intervals using cut as labels within aes using text.

x <- iris$Sepal.Length
bw <- 2 * IQR(x) / length(x)^(1/3)
num_bins <- diff(range(x)) / (2 * IQR(x) / length(x)^(1/3))

hist_breaks <- c(min(x)+ 0.1 - bw/2, rep(bw, num_bins+1)) %>% cumsum()

p <- iris %>% 
  mutate(label =cut(Sepal.Length, hist_breaks)) %>% 
  ggplot(aes(x = Sepal.Length, text = label)) +
    geom_histogram(binwidth = bw)
ggplotly(p, tooltip = c("count", "text"))

The plot

Check if boundaries are correct using p + geom_vline(xintercept = hist_breaks)

Roman
  • 17,008
  • 3
  • 36
  • 49