将多个文本标签添加到单个 facet_grid 面板
Posted
技术标签:
【中文标题】将多个文本标签添加到单个 facet_grid 面板【英文标题】:Adding multiple text labels to a single facet_grid panel 【发布时间】:2021-05-18 14:03:58 【问题描述】:在this 示例之后,我可以向每个分面网格添加一些文本,但在一个面板上,我需要在每组箱线图上使用 2 个单独的标签,类似于 stat_compare_means 生成的标签间距。我目前的逻辑每个面板只能容纳一个标签。如何防止它们重叠或为每个标签设置单独的坐标?
ID<-c('E5b','R6',"S22","E5b","R6","S22","E5b","R6","S22","E5b","R6","S22","E5b","R6","S22","E5b","R6",
"S22","E5b","R6","S22","E5b","R6","S22","E5b","R6","S22","E5b","R6","S22")
value<-c(1.02048033657553e-05, 7.03779542465882e-07, 3.51889771232941e-07, 5.69459095210849e-06, 5.42341995438904e-07,
1.08468399087781e-06, 1.15124329576991e-05, 2.34947611381614e-07, 4.69895222763228e-07, 1.02807349661977e-05,
2.12704861369607e-06, 0, 1.90550741185218e-06, 1.52440592948174e-06, 0, 1.23540828390671e-06, 4.11802761302236e-07,
0, 5.22781921260155e-06, 1.04556384252031e-06, 0, 1.71521997010029e-06, 0, 2.05826396412034e-06, 4.18012063828162e-06,
0, 7.60021934233022e-07, 2.93951950197596e-05, 0, 2.31458228502044e-07)
condition<-c("E","E","E","E","E","E","E","E","E","E","R","R","R","R","R","R","R","R","R",
"R","R","S","S","S","S","S","S","S","S","S")
family<-c("Unassigned","Unassigned","Siphoviridae","Unassigned","Unassigned","Siphoviridae","Unassigned","Unassigned",
"Siphoviridae","Unassigned","Unassigned","Siphoviridae","Unassigned","Unassigned","Siphoviridae","Unassigned",
"Unassigned","Siphoviridae","Unassigned","Unassigned","Siphoviridae","Unassigned","Unassigned","Siphoviridae",
"Unassigned","Unassigned","Siphoviridae","Unassigned","Unassigned","Siphoviridae")
seqlength<-NA
seqlength[1]<-'1941 kb'
seqlength[2]<-'1001 kb'
seqlength[3]<-'1214 kb'
df <- data.frame(ID,value,condition,family,seqlength)
p <- ggboxplot(df, x = "ID", y = "value",
color = "condition",
palette = "jco",add = "jitter")+
facet_wrap(~family,scales='free_x')+
scale_y_continuous(labels = comma)+
stat_compare_means(aes(group = condition),size=3,label="p.format") #label = "p.signif"
p + geom_text(
data = df,
mapping = aes(x = -Inf, y = -Inf, label = seqlength),
hjust = -2,
vjust = -40
)
【问题讨论】:
是来自 ggpubr 的 ggboxplot 吗? 【参考方案1】:对于分面注释,您需要为 ggplot 提供一个带有分面变量的数据框。但是,如果您将注释附加到数据的每一行,则文本将被过度绘制并且看起来很杂乱。一个好的解决方法是准备一个单独的表,其中只包含注释信息,因此每个标签只绘制一次:
#p <- ggboxplot(df, ]...
df_labels <- data.frame(
family = c("Unassigned","Unassigned","Siphoviridae"),
label = c('1941 kb', '1001 kb', '1214 kb'),
ID = c('E5b','R6',"S22"),
y = c(0.000028, 0.000028, 0.000028))
#hardcoded here but could make dynamic to taste by using max(df$value) etc.
p + geom_text(
data = df_labels,
mapping = aes(x = ID, y = y,
label = label)
)
【讨论】:
不错的答案 (+1) 只是想补充一点,在这种情况下,我们可以通过data = transform(df[1:3,], y = c(0.000028, 0.000028, 0.000028))
跳过中间数据帧构造。
很好的建议,因为在这种情况下我们需要三个类之间的数据循环,所以前三行提供了一个快捷方式。
看起来答案被接受了,然后又被拒绝了。它没有按预期工作吗?以上是关于将多个文本标签添加到单个 facet_grid 面板的主要内容,如果未能解决你的问题,请参考以下文章
R语言ggplot2可视化分面图(facet_grid)自定义缩小分面图标签栏的高度但是不改变标签栏标签文本的大小通过自定义设置可是胡图像的grobs参数
使用 purrr 时如何自定义 ggplot2 facet_grid 标签中的文本?