簡體   English   中英

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

[英]In ggplot2, how to add text by group in facet_wrap?

這是一個例子:

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)

我的問題是如何將類似第二個圖的文本添加到圖中。

在此輸入圖像描述 在此輸入圖像描述

您可以手動為文本創建另一個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)

在此輸入圖像描述

另一種選擇是動態計算相關性並使用因子變量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)

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM