David Z
David Z

Reputation: 7051

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

Here is an example:

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)

My question is how to add text like the second plot by group into the plot.

enter image description here enter image description here

Upvotes: 4

Views: 1967

Answers (2)

eipi10
eipi10

Reputation: 93871

Another option is to calculate the correlations on the fly and use the underlying numeric values of the factor variable g to place the text so that the red and blue labels don't overlap. This reduces the amount of code needed and makes label placement a bit easier.

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)

enter image description here

Upvotes: 3

JasonWang
JasonWang

Reputation: 2434

You can manually create another data.frame for your text and add the layer on the original plot.

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)

enter image description here

Upvotes: 5

Related Questions