R使用facet_wrap选择类别

时间:2017-06-30 13:03:07

标签: r ggplot2 facet-wrap

我正在尝试使用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")))

我想要做的是仅使用Subject来显示所选的facet_wrap?在这一刻, 它正在绘制所有Subject的情节。我如何只为主题308`` and 352`绘制?

由于

1 个答案:

答案 0 :(得分:1)

您只想在绘图前过滤数据

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