rggplot2facet-wrap

ggplot2 - include one level of a factor in all facets


I have some time series data that is facet wrapped by a variable 'treatment'. One of the levels of this 'treatment' factor the a negative control & I want to include it in every facet.

For example using R dataset 'Theoph':

data("Theoph")


head(Theoph)

Subject   Wt Dose Time  conc
1       1 79.6 4.02 0.00  0.74
2       1 79.6 4.02 0.25  2.84
3       1 79.6 4.02 0.57  6.57
4       1 79.6 4.02 1.12 10.50
5       1 79.6 4.02 2.02  9.66
6       1 79.6 4.02 3.82  8.58

Theoph$Subject <- factor(Theoph$Subject, levels = unique(Theoph$Subject)) # set factor order

ggplot(Theoph, aes(x=Time, y=conc, colour=Subject)) +
  geom_line() +
  geom_point() +
  facet_wrap(~ Subject)

How could I include the data corresponding to Subject '1' (the control) to be included in each facet? (And ideally removing the facet that contains Subject 1's data alone.)

Thank you!


Solution

  • To have a certain subject appear in every facet, we need to replicate it's data for every facet. We'll create a new column called facet, replicate the Subject 1 data for each other value of Subject, and for Subject != 1, set facet equal to Subject.

    every_facet_data = subset(Theoph, Subject == 1)
    individual_facet_data = subset(Theoph, Subject != 1)
    individual_facet_data$facet = individual_facet_data$Subject
    
    every_facet_data = merge(
      every_facet_data,
      data.frame(
        Subject = 1, 
        facet = unique(individual_facet_data$facet)
    ))
    
    plot_data = rbind(every_facet_data, individual_facet_data)
    
    library(ggplot2)
    ggplot(plot_data, aes(x=Time, y=conc, colour=Subject)) +
      geom_line() +
      geom_point() +
      facet_wrap(~ facet)
    

    enter image description here