首页 > 解决方案 > ggplot:给分面图中的主题添加相应的值

问题描述

我有一个包含多个主题的平面图,如下面的示例代码。我可以将数据框中的字母数字添加到图中的每个主题吗?

在此处输入图像描述

k <- structure(list(subject = c("subject1", "subject2", "subject1", 
"subject2", "subject1", "subject2", "subject1", "subject2"), 
    value = c(0.878597435209789, 0.0176290115770756, 0.985258898204333, 
    0.0347178797899928, 0.119612343633264, 0.0336586124505415, 
    0.0145236522430737, 0.0326404660694124), trial = c(4L, 4L, 
    5L, 5L, 6L, 6L, 7L, 7L), alpha = c(1,2,1,2,1,2,1,2)), row.names = c(NA, 
-8L), class = c("data.table", "data.frame"))


library(dplyr)
library(ggplot2)

k %>%
  mutate(label = ifelse(trial %in% c(5, 7), 'shock', '')) %>%
  ggplot(aes(x=trial,y=value, label = label)) +
  geom_point(aes(shape = label, color = label)) +
  geom_line()+
  geom_text(vjust = -1) + 
  facet_wrap(~factor(subject,levels=c(paste0('subject',1:2))))+
  scale_x_continuous(breaks = c(4:7)) + 
  scale_color_manual(values = c('red', 'blue')) + 
  theme_bw() + 
  guides(color=FALSE, shape = FALSE)

标签: rggplot2

解决方案


您只需要调用另一个geom_text()geom_label()在其aes()“alpha”变量中定义。为了获得第一个观察结果,然后按主题分组并切片第一行。

library(tidyverse)
               
k %>%
 mutate(label = ifelse(trial %in% c(5, 7), 'shock', '')) %>%
 ggplot(aes(x=trial,y=value, label = label)) +
 geom_point(aes(shape = label, color = label)) +
 geom_line()+
 geom_text(vjust = 1) + 
 # New lines below  
 geom_label(data = . %>% group_by(subject) %>% slice(1),
            aes(label = alpha), nudge_y = 0.08, nudge_x = 0.08) +
 # New lines above  
 facet_wrap(~factor(subject,levels=c(paste0('subject',1:2))))+
 scale_x_continuous(breaks = c(4:7)) + 
 scale_color_manual(values = c('red', 'blue')) + 
 theme_bw() + 
 guides(color=FALSE, shape = FALSE)

在此处输入图像描述


推荐阅读