Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

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

like image 408
David Z Avatar asked Mar 12 '23 23:03

David Z


1 Answers

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

like image 130
JasonWang Avatar answered Mar 15 '23 13:03

JasonWang