Search code examples
rggplot2facet-wrap

include plot of all data within each facet_wrap


Dataframe (borrowed from here):

df.test <- data.frame(id = rep(1:6, each = 50), x = rnorm(50*6, mean = 10, sd = 5), 
                 y = rnorm(50*6, mean = 20, sd = 10), 
                 z = rnorm(50*6, mean = 30, sd = 15))

Plot:

library(ggplot2)
ggplot(df.test, aes(x)) + geom_histogram() + facet_wrap(~id)

Request for assistance: I'd like to superimpose onto each of the facets the histogram of the entire data, to provide immediate comparison of each facet with the total dataset, if possible I'd like the whole dataset shown as a freq_poly():

ggplot(df.test, aes(x)) + geom_freqpoly()

enter image description here


Solution

  • You can exclude the facetting variable from the call to geom_freqpoly

    ggplot(df.test, aes(x)) + geom_histogram() + facet_wrap(~id) +
      geom_freqpoly(data = df.test[, "x", drop = FALSE], col = "red")
    

    enter image description here