Search code examples
rggplot2cowplot

How to create a faceting based on a column in second dataframe


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.


Solution

  • 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