ggplot2分面作图如果添加注释通常在每一个小图都会添加上

比如

df<-reshape2::melt(iris)
head(df)
library(ggplot2)
ggplot(df,aes(x=variable,y=value))+
geom_boxplot(aes(fill=variable),show.legend = F)+
facet_wrap('~Species')+
theme(axis.text.x = element_text(angle=60,vjust=0.5))+
geom_text(x=2,y=7,label="AAA")

ggplot2分面作图然后在其中一个添加注释_数据分析 image.png

如果我只想在第一个小图添加一个注释该如何实现呢?

经过搜索找到的办法基本都是为添加注释重新准备单独的一份数据

比如

df1<-data.frame(Species=c('versicolor'),
label=c("AAA"))
ggplot(df,aes(x=variable,y=value))+
geom_boxplot(aes(fill=variable),show.legend = F)+
facet_wrap('~Species')+
theme(axis.text.x = element_text(angle=60,vjust=0.5))+
geom_text(data=df1,x=2,y=7,aes(label=label))

ggplot2分面作图然后在其中一个添加注释_数据分析_02 image.png

这样就只在第二个小图上添加了注释

这里需要注意的是新构造的数据集列名需要和用来作图的数据集分面的变量的列名一致。

参考链接

​https://r-graphics.org/recipe-annotate-facet​​​

​https://taipapamotohus.com/post/different-segment-to-each-facet-in-ggplot/​​​

欢迎大家关注我的公众号

小明的数据分析笔记本