Search code examples
rggplot2histogram

Add a geom_vline to the tallest histogram bin in ggplot


How can I add a geom_vline on the tallest bin of a histogram?

The following is not what I want, because it goes by max(x).

library(ggplot2)

set.seed(15)
df <- data.frame(x=rnorm(100,5,2))

df |> 
  ggplot(aes(x=x))+ 
  geom_histogram(binwidth = 1) +
  stat_bin(geom = "vline", aes(xintercept = after_stat(max(x) ) ), binwidth = 1, color = "red")

Created on 2023-05-04 with reprex v2.0.2

But I want the x value that corresponds to max(y).

Desired Output

enter image description here


Solution

  • Using e.g. which.max you could do:

    library(ggplot2)
    
    set.seed(15)
    df <- data.frame(x = rnorm(100, 5, 2))
    
    df |>
      ggplot(aes(x = x)) +
      geom_histogram(binwidth = 1) +
      stat_bin(
        geom = "vline", aes(xintercept = after_stat(x[which.max(count)])),
        binwidth = 1, color = "red"
      )