R 对所选类别使用 facet_wrap

R using facet_wrap for selected categories

我正在尝试使用 facet_wrap 绘制单独的地块。

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")))

我想做的是仅使用 facet_wrap 可视化选定的 Subject?在这一刻, 它正在绘制所有 Subject 的地块。我如何只为说主题 308`` and352` 绘图?

谢谢

您只想在绘图前过滤数据

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")))