在ggplot2中,如何在facet_wrap中按组添加文本?

在ggplot2中,如何在facet_wrap中按组添加文本?,r,ggplot2,R,Ggplot2,以下是一个例子: library(ggplot2) set.seed(112) df<-data.frame(g=sample(c("A", "B"), 100, T), x=rnorm(100), y=rnorm(100,2,3), f=sample(c("i","ii"), 100, T)) ggplot(df, aes(x=x,y=y, colour=factor(g)))+ geom_point()+geom_smo

以下是一个例子:

library(ggplot2)
set.seed(112)
df<-data.frame(g=sample(c("A", "B"), 100, T),
           x=rnorm(100),
           y=rnorm(100,2,3),
           f=sample(c("i","ii"), 100, T))
ggplot(df, aes(x=x,y=y, colour=factor(g)))+
geom_point()+geom_smooth(method="lm", fill="NA")+facet_wrap(~f)
库(ggplot2)
种子集(112)

df您可以手动为文本创建另一个data.frame,并在原始绘图上添加图层

df_text <- data.frame(g=rep(c("A", "B")), x=-2, y=c(9, 8, 9, 8),
                      f=rep(c("i", "ii"), each=2),
                      text=c("R=0.2", "R=-0.3", "R=-0.05", "R=0.2"))

ggplot(df, aes(x=x,y=y, colour=factor(g))) +
  geom_point() + geom_smooth(method="lm", fill="NA") +
  geom_text(data=df_text, aes(x=x, y=y, color=factor(g), label=text),
  fontface="bold", hjust=0, size=5, show.legend=FALSE) + 
  facet_wrap(~f)

df_text另一个选项是动态计算相关性,并使用因子变量
g
的基本数值来放置文本,以便红色和蓝色标签不会重叠。这减少了所需的代码量,并使标签放置更加容易

library(dplyr)

ggplot(df, aes(x=x, y=y, colour=g)) +
  geom_point() + 
  geom_smooth(method="lm", fill=NA) +  # Guessing you meant fill=NA here
  #geom_smooth(method="lm", se=FALSE)  # Better way to remove confidence bands
  facet_wrap(~f) +
  geom_text(data=df %>% group_by(g, f) %>% summarise(corr = cor(x,y)), 
            aes(label=paste0("R = ", round(corr,2)), y = 10 - as.numeric(g)), 
            x=-2, hjust=0, fontface="bold", size=5, show.legend=FALSE)

要对齐文本,可以将
hjust=0
放入
geom\u文本中。我正要发布一个几乎相同的答案:-)没问题,@DavidZ!您的意思是
fill=NA
(而不是
fill=“NA”
)。前者将消除置信带。但是,您也可以执行
se=FALSE
,以防止首先添加置信区间。