1

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

Sasha
  • 5,783
  • 8
  • 33
  • 37

2 Answers2

0

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.

andrewb
  • 106
  • 4
  • 1
    That's not what I want. I need the actual histograms to be stacked in each plot as in the second example. Changing `scale` only changes the vertical distance between the plots, but each plot remains unchanged. – Sasha May 25 '21 at 05:17
  • Oh sorry the wording was kind confusing. Usually that would be `position = "stack"` but I don't think that works with `geom_density_ridges`. If your issue is aesthetics I would try different themes – andrewb May 25 '21 at 20:30
0

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?