Skip to content

Instantly share code, notes, and snippets.

@low-decarie
Created November 13, 2013 13:42
Show Gist options
  • Save low-decarie/7449296 to your computer and use it in GitHub Desktop.
Save low-decarie/7449296 to your computer and use it in GitHub Desktop.
ggplot2 approach to plotting the results of the candisc function found in the candisc package with 95% confidence ellipses. Needs editing to be completely compatible with candisc.
gg.candisc.plot <- function(candisc.object){
# Plot with ellipses using ggplot2 ####
require(grid)
require(ggplot2)
require(devtools)
require(digest)
#For info : http://stackoverflow.com/questions/2397097/how-can-a-data-ellipse-be-superimposed-on-a-ggplot2-scatterplot
source_url("https://raw.github.com/low-decarie/FAAV/master/r/stat-ellipse.R")
#Nicer theme
theme_set(theme_bw())
#Basic score plot
labels <- names(candisc.object$scores)[1]
can.plot <- qplot(data=candisc.object$scores,
x=Can1,
y=Can2,
colour=get(labels))+
stat_ellipse()+ #Add ellipses
coord_equal()
#Add arrows
#Create arrow coordinates
arrow.coord <- data.frame(x=0,y=0,
xend=candisc.object$structure[,1],yend=candisc.object$structure[,2],
variable=row.names(candisc.object$structure))
#Enlarge arrows
enlarge <- 3
arrow.coord$xend <- enlarge*arrow.coord$xend
arrow.coord$yend <- enlarge*arrow.coord$yend
#Plot arrows
can.plot <- can.plot+geom_segment(data=arrow.coord,
colour=I("black"),
aes(x=x,
y=y,
xend=xend,
yend=yend),
arrow = arrow(length = unit(0.5,"cm")))
#Add arrow labels
can.plot <- can.plot+geom_text(data=arrow.coord,
colour=I("black"),
aes(x=xend,
y=yend,
label=variable,
hjust=0.5,
vjust=0.5))
print(can.plot)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment