Search code examples
rggplot2facet-wrap

Overlay density plot to each existing facet wrapped density plot in ggplot2?


I have a dataframe with ~37000 rows that contains 'name' in string format and 'UTCDateTime' in posixct format and am using it to produce a facet wrapped density plot of time grouped by the names:

enter image description here

I also have a separate density plot of posixct datetime data from an entirely different dataframe:

enter image description here

I want to overlay this second density plot on each individual facet_wrapped plot in the first density plot. Is there a way to do that? In general, if I have plots of any kind that are facet wrapped and another plot of the same type but different data that I want to overlay on each facet of the facet wrap, how do I do so?


Solution

  • This should in theory be as simple as not having the column that you're facetting by in the second dataframe. Example below:

    library(ggplot2)
    
    ggplot(iris, aes(Sepal.Width)) +
      geom_density(aes(fill = Species)) +
      geom_density(data = faithful,
                   aes(x = eruptions)) +
      facet_wrap(~ Species)
    

    Created on 2020-08-12 by the reprex package (v0.3.0)

    EDIT: To get the densities on the same scale for the two types of data, you can use the computed variables using after_stat()*:

    ggplot(iris, aes(Sepal.Width)) +
      geom_density(aes(y = after_stat(scaled),
                       fill = Species)) +
      geom_density(data = faithful,
                   aes(x = eruptions,
                       y = after_stat(scaled))) +
      facet_wrap(~ Species)
    

    * Prior to ggplot2 v3.3.0 also stat(variable) or ...variable....