r - 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)
解决方案
您只需要调用另一个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)
推荐阅读
- c - 从 MPI 中的文本文件中读取
- powerbi - 如果我想将 Power BI 函数用作报表的轴值,它的返回类型应该是什么
- r - 在单独的数据框中使用日期范围过滤 - R
- javascript - 尝试从 fullcalendar 文档中获取 eventRender 中显示的工具提示
- api - 错误:连接 ECONNREFUSED 127.0.0.1:8000
- .net - 日期时间转换格式错误(日光?)
- reactjs - 使用 react-leaflet-markercluster 时出现错误“TypeError:超级表达式必须为 null 或函数,而不是对象”
- c# - SQL 查询在 SQL Server 和 C# 中返回的结果不同
- sql-server - SQL Server, Qlik Sense naming convention
- php - 结尾没有点的链接的正则表达式