user237554
user237554

Reputation: 89

height of ridgeline plot not scaling to data

I have two distributions that are moving in opposite directions over time - foo1 is going up, and foo2 is going down. However, the max value of foo1 is only half the min value of foo2. Is there a way to capture this difference in geom_density_ridges? In other words, how do I get the panels to not scale independently, but relative to each other? Right now they seem to be scaling independently and that's very misleading, as it gives the impression the max values for the two foo classes are the same. I tried

geom_density_ridges(panel_scaling = FALSE) 

Didn't raise an error, but didn't do anything either.

See sample:

fy_list = c(1986,1987,1988,1989,1990,1991,1992,1993,1994,1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017)

yrs1 = rep(fy_list, times=c(6,7,10,7,4,7,11,18,19,16,13,13,15,17,15,17,17,15,16,15,15,15,16,20,18,16,19,16,17,15,16,16))
foo1 = rep("foo1", times=457)
df1 = data.frame(yrs1, foo1)

yrs2 = rep(fy_list, times=c(67,62,58,63,64,57,54,49,44,46,49,48,45,47,45,43,41,40,37,38,36,35,33,32,33,32,30,32,30,34,33,33))
foo2 = rep("foo2", times=1390)
df2 = data.frame(yrs2, foo2)

df1 <- rename(df1, bin = foo1, yrs = yrs1)
df2 <- rename(df2, bin = foo2, yrs = yrs2)
df_test <- rbind(df1, df2)

p <- ggplot(df_test, aes(x = yrs, y = bin)) + 
  geom_density_ridges()+
  labs(x = "fiscal year", y = "foo(test)")+
  theme_minimal()

plot from code

Upvotes: 0

Views: 688

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173858

It's pretty straightforward to calculate the relative densities manually and use stat = "identity"

tidyr::pivot_longer(data.frame(yrs = density(df1$yrs)$x,
                      foo1 = density(df1$yrs)$y * nrow(df1)/nrow(df2),
                      foo2 = density(df2$yrs)$y), -1, names_to = "bin") %>%
  ggplot(aes(x = yrs, y = bin, height = value)) + 
  geom_density_ridges(stat = "identity")+
  labs(x = "fiscal year", y = "foo(test)")+
  theme_minimal()

enter image description here

Upvotes: 2

Related Questions