Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Quick" Scatterplot Legend with ggplot? [duplicate]

Tags:

r

ggplot2

Possible Duplicate:
ggplot2: Adding Regression Line Equation and R2 on graph

I'm graphing data in a scatter plot with

ggplot(work.rootsfnp.h1, aes(x=fnpltrfac, y=rootsscore, group=1)) + 
  geom_smooth(method=lm, se = F) + geom_point(shape=1)

Is there a "quick" way to add a basic legend that includes the formula of the line of best fit as well as the correlation coefficient?

like image 960
Jeff Erickson Avatar asked Mar 26 '26 23:03

Jeff Erickson


1 Answers

Not quick, but possible:

First, fit a model with lm

model <- lm(mpg ~ wt + factor(cyl), data=mtcars)

Then extract the coefficients and R^2, and construct expressions for each

x <- coef(model)
intercept <- signif(x[1], 3)
terms <- paste(signif(x[-1], 3), names(x[-1]), sep="*", collapse= " + ")
e1 <- paste(intercept, terms, collapse = " + ")
e2 <- paste("R^2 = ", round(summary(model)$r.squared, 3))

Finally, plot with ggplot and use annotate to place labels.

ggplot(mtcars, aes(x=wt, y=mpg)) + 
    geom_point() + 
    geom_smooth(method=lm) +
    annotate("text", label=e1, x=max(mtcars$wt), y=max(mtcars$mpg), 
             hjust=1, size=3, vjust=0) +
    annotate("text", label=e2, x=max(mtcars$wt), y=max(mtcars$mpg), 
             hjust=1, size=3, vjust=1)

enter image description here

like image 85
Andrie Avatar answered Mar 29 '26 12:03

Andrie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!