0

I am trying to use facet_wrap to plot indvidual plots.

library(lme4)
library(dplyr)
library(tibble)

# Convert to tibble for better printing. Convert factors to strings
sleepstudy <- sleepstudy %>% 
as_tibble() %>% 
mutate(Subject = as.character(Subject))

xlab <- "Days of sleep deprivation"
ylab <- "Average reaction time (ms)"

ggplot(df_sleep) + 
 aes(x = Days, y = Reaction) + 
 stat_smooth(method = "lm", se = FALSE) +
 # Put the points on top of lines
  geom_point() +
 facet_wrap("Subject") +
 labs(x = xlab, y = ylab) + 
 theme(axis.text=element_text(size=0.02),
       axis.title=element_text(size=0.02,face="bold"),
       plot.title = element_text(size=0.02)) +
theme(strip.text.x = element_text(size = 8), 
    strip.background = element_rect(fill="lightblue", colour="black",size=0.2)) +
theme(strip.text.x = element_text(margin = margin(0.02, 0, 0.02, 0, "cm")))

What I want to do is to only visualise selected Subject using facet_wrap? At the moment, it is plotting plots of all the Subject. How do I plot only for say subject 308`` and352`?

Thanks

user53020
  • 889
  • 2
  • 10
  • 33
  • 2
    Sounds like you want to plot a subset of the data, so you should subset the datasets rather than using the entire dataset for plotting. Like, e.g., put `subset(df_sleep, Subject %in% c(308, 352) )` in the `data` argument of `ggplot2`. – aosmith Jun 30 '17 at 13:07
  • Okay. Thanks. It seems more straightforward than what I thought. – user53020 Jun 30 '17 at 14:04

1 Answers1

1

You just want to filter your data before plotting

library(lme4)
library(dplyr)
library(tibble)
library(ggplot2)

# Convert to tibble for better printing. Convert factors to strings
sleepstudy <- sleepstudy %>% 
as_tibble() %>% 
mutate(Subject = as.character(Subject))

xlab <- "Days of sleep deprivation"
ylab <- "Average reaction time (ms)"

sleepstudy %>%
filter(Subject %in% c("308", "352")) %>%
ggplot(.) + 
 aes(x = Days, y = Reaction) + 
 stat_smooth(method = "lm", se = FALSE) +
 # Put the points on top of lines
  geom_point() +
 facet_wrap("Subject") +
 labs(x = xlab, y = ylab) + 
 theme(axis.text=element_text(size=0.02),
       axis.title=element_text(size=0.02,face="bold"),
       plot.title = element_text(size=0.02)) +
theme(strip.text.x = element_text(size = 8), 
    strip.background = element_rect(fill="lightblue", colour="black",size=0.2)) +
theme(strip.text.x = element_text(margin = margin(0.02, 0, 0.02, 0, "cm")))
Hanjo Odendaal
  • 1,395
  • 2
  • 13
  • 32