Learn R Programming

SciencesPo (version 1.3.9)

lm2eqn: Linear model to equation style

Description

Produces a text equation style to be added in plots.

Usage

lm2eqn(.data, x, y, spaced = TRUE)

Arguments

.data
The data.frame object.
x
The independent variable(s).
y
The dependent variable.
spaced
A logical value indicating if spaces should be added; default is TRUE.

Examples

Run this code
lm2eqn("mtcars","wt","mpg")


data(Presidents)

Presidents <- transform(Presidents, ratio = winner.height/opponent.height)
Presidents <- transform(Presidents, selected = ifelse(winner %in% c("Barack Obama"),1,0))

# subsetting election > 1824
Presidents = subset(Presidents, election > 1824 & !is.na(ratio))

selected=Presidents[Presidents$selected==1,]
myeqn=lm2eqn("Presidents","ratio","winner.vote")

ggplot(Presidents, aes(x=ratio,y=winner.vote,colour=selected)) +
 geom_text(data=selected,aes(label=winner),hjust=-0.1) +
 geom_smooth(method=lm, colour="red", fill="gold") +
 geom_point(size=5, alpha=.7) +
annotate(geom='text',x=1.1,y=64,size=7,label=myeqn,family='Times',fontface='italic') +
xlim(.9,1.2) + ylim(38, 65) +
 scale_colour_gradientn(guide="none" , colours=c("black","red")) +
xlab("Presidential Height Ratio") +
 ylab("Relative Support for President")

Run the code above in your browser using DataLab