1

my code is quite similar to the following example. I have categories (internally stored as factors) and I need to plot multiple graphs. When I plot them the tich for the y-axis are not in the exact same height as you can see in the figure. Is there a solution for this?

library(ggplot2)
library('grid')
a=ggplot(iris, aes(x = Sepal.Length, y = Species)) + geom_density_ridges()
b=ggplot(iris, aes(x = Sepal.Width, y = Species)) + geom_density_ridges()


test=cbind(ggplotGrob(a), ggplotGrob(b),size="last")
grid.draw(test)

enter image description here.imgur.com/gTshi.jpg

Fabrizio
  • 927
  • 9
  • 20

2 Answers2

2

There is an ..ndensity.. option for height argument

library(devtools)

install_github("clauswilke/ggridges")

a <- ggplot(iris, aes(x = Sepal.Length, y = Species, height = ..ndensity..)) + geom_density_ridges()

b <- ggplot(iris, aes(x = Sepal.Width, y = Species, height = ..ndensity..)) + geom_density_ridges()

test <- cbind(ggplotGrob(a), ggplotGrob(b),size="last")

grid.draw(test)

k8isdead
  • 21
  • 5
  • Why do you say *it doesn't work with the CRAN package version*? My `ggridges` package version is 0.5.1, the same as CRAN's and your code did work. Upvote, BTW. – Rui Barradas Sep 02 '19 at 12:46
  • idk, probably something was wrong with my CRAN package installation, i'll check. – k8isdead Sep 02 '19 at 13:58
  • 1
    yep, i've reinstalled the package from CRAN and it works just fine, so I've edited the initial comment in order not to confuse anyone. – k8isdead Sep 02 '19 at 14:18
  • 1
    It's a very good solution and I would like to endorse it more (I upvoted it). Sorry if I didn't add the "accepted answer". It works also with separate plots (one plot for each different file) without the need to put them in a grid. – Fabrizio Sep 03 '19 at 07:16
1

A possible solution is to reshape the data from wide to long first, in this case with package reshape2, then use ggplot2's faceting.

library(ggplot2)
library(ggridges)

long_iris <- reshape2::melt(iris[c(1, 2, 5)], id.vars = "Species")

g <- ggplot(long_iris) + 
  geom_density_ridges(aes(x = value, y = Species)) +
  theme_ridges() +
  facet_wrap(~ variable)

g

enter image description here

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66