Guy
Guy

Reputation: 4055

ggplot: add mathematical expression to different facets in different position

I'm trying to add different texts to different facets but since the scales are different, I'd like to position them in the appropriate places for each facet. geom_text allows me to play with the position but couldn't turn the r^2 into a mathematical expression ("2" should be supperscript). Annotate allows me present the mathematical expression but not to place the texts in different positions (get an error message).

Here is a reproducible example:

df1=data.frame(x=c(1,10,100), y=c(1,10,100), fct=c("a", "b", "c"))
df2=data.frame(fct=c("a", "b", "c"), r2=c("r^2", "r^2", "r^2"), labs=c(7, 3, 8))
lb <- c(paste("r^2 == ", df2[1,3]), paste("r^2 == ", df2[2,3]),paste("r^2 == ", df2[3,3]))


#option 1 with geom_text
ggplot(df1, aes(x=x, y=y))+geom_point(data=df1, aes(x=x, y=y, color=fct))+facet_grid(~fct, scales='free')+geom_text(data=df2, aes(x=c(1, 10, 100), y=25, label=paste(r2,'=',labs), parse=T))

#option 2 with annotate
ggplot(df1, aes(x=x, y=y))+geom_point(data=df1, aes(x=x, y=y, color=fct))+facet_grid(~fct, scales='free')+annotate("text", x=1, y=20, label=lb, parse=TRUE)

Thanks for the help,

Guy

Upvotes: 0

Views: 425

Answers (1)

lukeA
lukeA

Reputation: 54237

ggplot warns you in the 1st example:

Warning: Ignoring unknown aesthetics: parse

If you put if outside the aes mappings, then you'll get:

ggplot(df1, aes(x=x, y=y))+
  geom_point(data=df1, aes(x=x, y=y, color=fct))+
  facet_grid(~fct, scales='free')+
  geom_text(data=df2, aes(x=c(1, 10, 100), y=25, label=paste(r2,'==',labs)), parse=T)

enter image description here

Upvotes: 1

Related Questions