Skip to content

Instantly share code, notes, and snippets.

@emhart
Created May 1, 2012 04:48
Show Gist options
  • Save emhart/2565120 to your computer and use it in GitHub Desktop.
Save emhart/2565120 to your computer and use it in GitHub Desktop.
ggplot2 SEM model example
###Generate box coords
###A function to generat a blank box for use with geom_path()
box_coords <- function(x,y,size){
b.x <- c(rep(x,2) - (size[1] / 2),rep(x,2) + (size[1] / 2))
b.x[5] <- b.x[1]
b.y <- c(y-(size[2] / 2),rep(y,2)+(size[2] / 2),y-(size[2] / 2))
b.y[5] <- b.y[1]
rmat <- data.frame(cbind(b.x,b.y))
colnames(rmat) <- c("x","y")
return(rmat)
}
###Finds the center point of a box object
box_centroid <- function(box)
{
x.c <- min(box[,1])+ (diff(range(box[,1]))/2)
y.c <- min(box[,2]) + (diff(range(box[,2]))/2)
return(c(x.c,y.c))
}
caus<- box_coords(1,0,c(2,1))
predb <- box_coords(6,0,c(2,1))
spb <- box_coords(10,2,c(2,1))
reb <- box_coords(10,-2,c(2,1))
text.df <- c("Pond C.V.", "Predators","Spine","Growth rate")
text.dfc <- data.frame(rbind(box_centroid(caus),box_centroid(predb),box_centroid(spb),box_centroid(reb)))
text.df <- cbind(text.df,text.dfc)
sem.p <- ggplot(caus,aes(x=x,y=y))+geom_path()+geom_path(data=predb,aes(x=x,y=y))+xlim(0,12)+ylim(-3,3)+theme_set(theme_white())
sem.p <- sem.p + geom_path(data=spb,aes(x=x,y=y)) + geom_path(data=reb,aes(x=x,y=y))
sem.p <- sem.p + geom_text(data=text.df,aes(X1,X2,label=text.df))
sem.p <- sem.p + geom_segment(aes(x=2,y=0,xend=5,yend=0,size=1.5*.788,colour="#E42217"),arrow=arrow(length=unit(.45,"cm")))+ scale_size_identity()+scale_colour_identity()
sem.p <-sem.p + geom_segment(aes(x=7,y=.5,xend=9,yend=1.5,size=1.5*.681,colour="#228B22"),arrow=arrow(length=unit(.45,"cm")))+ scale_size_identity()+scale_colour_identity()
sem.p <-sem.p + geom_segment(aes(x=7,y=-.5,xend=9,yend=-1.5,size=1.5*.788,colour="#228B22"),arrow=arrow(length=unit(.45,"cm")))+ scale_size_identity()+scale_colour_identity()
sem.p <-sem.p + geom_segment(aes(x=2,y=.5,xend=9,yend=2,size=1.5*.256 ,colour="#E42217",linetype=2),arrow=arrow(length=unit(.45,"cm")))+ scale_size_identity()+scale_colour_identity()+scale_linetype_identity()
sem.p <-sem.p + geom_segment(aes(x=2,y=-.5,xend=9,yend=-2,size=1.5*.052 ,colour="#E42217",linetype=2),arrow=arrow(length=unit(.45,"cm")))+ scale_size_identity()+scale_colour_identity()+scale_linetype_identity()
sem.p <-sem.p + geom_segment(aes(x=10,y=-1.5,xend=10,yend=1.5,size=1.5*.197 ,colour="#228B22",linetype=2),arrow=arrow(length=unit(.45,"cm")))+ scale_size_identity()+scale_colour_identity()+scale_linetype_identity()
sem.p <-sem.p + geom_segment(aes(x=10,y=1.5,xend=10,yend=-1.5,size=1.5*.197 ,colour="#228B22",linetype=2),arrow=arrow(length=unit(.45,"cm")))+ scale_size_identity()+scale_colour_identity()+scale_linetype_identity()
sem.p
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment