'Stacked histograms with ggridges package in R

The following code produces histograms that overlap. How can I modify this code to make the histograms stack on top of each other?

library(tidyverse)
library(ggridges)

iris %>% 
      pivot_longer(cols = -Species,
                   names_to = "Param", 
                   values_to = "Value") %>% 
      ggplot(aes(x = Value, y = Param))+
      geom_density_ridges(aes(fill = Species),
                          stat = "binline",
                          alpha = 0.5)

enter image description here

I can achieve a desired effect using geom_histogram and facet_wrap as shown below, but from aesthetics perspective prefer a solution using ggridges.

iris %>% 
  pivot_longer(cols = -Species,
               names_to = "Param", 
               values_to = "Value") %>% 
  ggplot(aes(x = Value))+
  geom_histogram(aes(fill = Species),  
                 position = position_stack(), 
                 alpha = 0.5) +
  facet_wrap(~Param,ncol = 1,scales = "free_y")

enter image description here



Solution 1:[1]

If you add scale = 1 to your geom_density_ridges call then the plots will just touch (see here). You can also have scale values less than 1 to increase separation.

Solution 2:[2]

it sounds trivial, but I tried exchanging

position = position_stack()

with

position = "stack"

in your dplyr code, and it worked.

Is this what you wanted?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 andrewb
Solution 2