0

I want to create a graph that looks like:

Now I found the cowplot package which gave me a quite similar result.

library(ggplot2)
library(cowplot)
library(data.table)
library(ggridges)

d = data.table(iris)

a = ggplot(data = d, aes(x=Sepal.Length, y=..count..)) +
  geom_density_line() + 
  geom_density_line(data = d[Species == "virginica"], aes(), fill="lightblue", color="darkblue") +
  theme_bw()

b = ggplot(data = d, aes(x=Sepal.Length, y=..count..)) +
  geom_density_line() + 
  geom_density_line(data = d[Species == "versicolor"], aes(), fill="lightgreen", color="darkgreen") +
  theme_bw()

cowplot::plot_grid(a, b, labels=NULL)

The result looks like:

But, there are two points that bother me:

  • It has a y-axix in both plots
  • With my real data where I have up to 10 grids, the code becomes very long

I think it must be possible to use facet_grid(), facet_wrap() or something similar to achieve this. But I don't know how I can use a column from the dataframe of the second geometry to create these subsets without changing/losing the greyish background plot.

Marco_CH
  • 3,243
  • 8
  • 25

1 Answers1

2

We can feed one layer a version of the data without Species, so it calculates the whole thing as our background context, and another layer that includes Species to map that to fill and to the appropriate facet.

library(ggplot2); library(ggridges)
ggplot(data = iris, aes(Sepal.Length, ..count..)) +
  geom_density_line(data = subset(iris, select = -Species)) +
  geom_density_line(aes(fill = Species)) +
  facet_wrap(~Species)

enter image description here

Jon Spring
  • 55,165
  • 4
  • 35
  • 53
  • Perfect, thank you very much. Do you know if there is a way to prevent a behavior like with setosa (setosa-only is higher then full distribution)? – Marco_CH Jan 28 '22 at 21:26
  • 1
    That's an artifact of the line smoothing. You can control the degree of smoothing using the `adjust` parameter, for instance `adjust = 2` to smooth it twice as much. – Jon Spring Jan 28 '22 at 22:02