First of all, I'm beginner R user. I wanna add R-square and p-value in my chart. But, in a line just separate by a comma. Attached is the code I'm trying to use.
ggplot(data, aes(x,y))+
geom_point(shape=1,size=4)+
stat_smooth(method="lm",size=0.6,se=FALSE,colour="black")+
annotate("text",x=30,y=0.45,label=c("italic(r^{2}==0.151)","p==0.226"),parse=TRUE)+
theme_bw(base_size = 12)
However, I receive this error:
Error: Aesthetics must be either length 1 or the same as the data (1): label
Thanks!
When you want to parse multiple expressions as a single expression, you can use paste
to take the expressions and put them on a single line. As explained in the other answer, right now you are giving annotate
two distinct expressions but only one set of x, y coordinates and this is causing the error.
Without a comma, the single expression could look like
paste("italic(r^{2}) ==", 0.151, "~p==.226")
This is what you would put as your label in annotate
. The additional tilde makes a space between the first and second expressions.
To include the comma, you need list
in plotmath. In plotmath, list
means a comma separated lists (see ?plotmath
for all the available features). Essentially this means wrapping your entire expression in list
inside paste
.
paste("list(italic(r^{2}) ==", 0.151, ", p==.226)")
And so your annotate code would be
+ annotate("text", x=30, y=0.45, label=paste("list(italic(r^{2}) ==", 0.151, ", p==.226)"), parse=TRUE)