Skip to content

Instantly share code, notes, and snippets.

@dwbapst
Created February 5, 2018 02:42
Show Gist options
  • Select an option

  • Save dwbapst/7de27f14d957cc4397653dd6a14eb5c8 to your computer and use it in GitHub Desktop.

Select an option

Save dwbapst/7de27f14d957cc4397653dd6a14eb5c8 to your computer and use it in GitHub Desktop.
Creating your own biplot for ordinations (e.g. ecological matrices with environmental data) isn't that hard - hardest part is figuring out how to get zero to line-up
# x is the score for the horizontal axis, xx is the loading for that axis
# y is the score for the vertical axis, yy is the loading for that axis
# and the labels for each can also be set
myBiPlot<-function(x,y,xx,yy
,xlab="",ylab=""
,xxlab="",yylab=""){
oldPar<-par(no.readonly=TRUE)
par(mar=c(5,5,5,5))
#
rangeBalance<-function(data){
range<-range(c(0,data))
range/diff(range)
}
#
balanceX<-rangeBalance(xx)*diff(range(c(0,x)))
balanceXX<-rangeBalance(x)*diff(range(c(0,xx)))
rangeX<-extendrange(c(x,balanceX,0))
rangeXX<-extendrange(c(xx,balanceXX,0))
#
balanceY<-rangeBalance(yy)*diff(range(c(0,y)))
balanceYY<-rangeBalance(y)*diff(range(c(0,yy)))
rangeY<-extendrange(c(y,balanceY,0))
rangeYY<-extendrange(c(yy,balanceYY,0))
#
plot(x,y
,xlim=rangeX
,ylim=rangeY
,xlab=xlab
,ylab=ylab)
par(new=TRUE)
plot(xx,yy,type="n",
,xlim=rangeXX
,ylim=rangeYY
,xlab="",ylab=""
,xaxt="n",yaxt="n")
axis(3);axis(4)
mtext(xxlab,side=3,line=3)
mtext(yylab,side=4,line=3)
arrows(x0=0,y0=0,
length=0.1,
x1=xx,y1=yy)
par(oldPar)
}
# an example
set.seed(1)
x<-rnorm(20)*10
y<-rnorm(20)*10
xx<-rnorm(4)
yy<-rnorm(4)+1
myBiPlot(x=x,y=y,xx=xx,yy=yy,
xlab="X Scores",ylab="Y Scores",
xxlab="X Loadings",yylab="Y Loadings")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment