Search code examples
rggplot2ggridges

Disable Histogram Scaling in ggplot2 ggridges


Please have a look at the following histograms of temperature for the various months of the year. I limit the temperature to 50+ degrees to purposefully force some of the the histograms to be small, for the colder months. Make note of months 1, 2, and 3, so small they barely register on the facet plot.

library(nycflights13)
library(ggplot2)
library(dplyr)
ggplot(weather %>% filter(temp > 50), aes(temp)) +
  geom_histogram() + 
  facet_wrap(~ as.factor(month))

This ggridges package is awesome. It also plots histograms. By default it scales the histograms such that the y-values are relatively the same height. How do I disable this? I know I have to somehow specify height = ..stat_identity_count.. or height = ..y.. but I've tried every conceivable combination and can't figure it out. In the plot below months 1, 2, and 3, which were barely noticeable above, have now been scaled to become enormous. I want the height of the y-axis to reflect actual counts of their respective histogram bins. Like the original facet wrap example.

library(ggridges)
ggplot(weather %>% filter(temp > 50), aes(x = temp, y = as.factor(month))) + 
  geom_density_ridges()

and I do understand it can often be easier to compare histograms by ..density.. vs absolute counts, but that's not what's desired in my current analysis.


Solution

  • This can be done with stat_density(), using the ..count.. aesthetic instead of ..density..:

    ggplot(weather %>% filter(temp > 50),
           aes(x = temp, y = as.factor(month),
               group = as.factor(month), height = ..count..)) + 
      geom_density_ridges(stat = "density")
    

    enter image description here