Created
September 2, 2017 17:13
-
-
Save mbusigin/d50ff1e99c2e371823725567316a144b to your computer and use it in GitHub Desktop.
R function for multiplotting (overplotting), either on the same, or differing axes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
multiplot = function(r, legend.loc="topleft", legend.cex=1, overplot=F, plotSecondAxis=F, s_lty=1, plotfunc=recplot, legend=T, pointMax=F, pointLast=F, legendLast=F, legendLastRoundDigits=0 ) | |
{ | |
r = na.omit(r) | |
for ( x in names(r) ) | |
{ | |
n = r[,x] | |
m = n | |
r[,x] = m | |
} | |
print(tail(r)) | |
colours = RColorBrewer::brewer.pal(length(names(r)), "Dark2") | |
colours[ 1 ] = "dodgerblue3" | |
colours[ 3 ] = "black" | |
firstplot = T | |
count = 1 | |
for ( x in names(r) ) | |
{ | |
if ( firstplot ) | |
{ | |
if ( overplot == T ) | |
{ | |
plotfunc(r[,x], main="") | |
} | |
else | |
{ | |
plotfunc(r[,x], ylim=c(min(r), max(r)), main="") | |
} | |
firstplot = F | |
} | |
else | |
{ | |
if ( overplot == F ) | |
{ | |
lines(r[,x], col=colours[count], lty=s_lty) | |
} | |
else | |
{ | |
par(new=T, xaxt="n", yaxt="n") | |
plot.zoo(r[,x], col=colours[count]) | |
if ( plotSecondAxis == T ) | |
{ | |
par(xaxt="s", yaxt="s") | |
axis(4, col=colours[count] )#, line=count - 1) | |
par(xaxt="n", yaxt="n") | |
} | |
} | |
} | |
if ( pointMax == T ) | |
{ | |
localMax = r[ which.max(r[,x]), x ] | |
print( paste("Maximum for ", x, localMax)) | |
points( localMax, pch=16, col=colours[count] ) | |
} | |
if ( pointLast == T ) | |
{ | |
localLast = last(r[ ,x ]) | |
print( paste("Last for ", x, localLast)) | |
points(localLast, pch=16, col=colours[count] ) | |
} | |
count = count + 1 | |
} | |
par(xaxt="s", yaxt="s") | |
if ( legend == T ) | |
{ | |
legendLabels = names(r) | |
if ( legendLast == T ) | |
{ | |
newLegend = c() | |
for ( x in names(r) ) | |
{ | |
newLegend = c(newLegend, paste(x, ': ', round(last(r[,x]), legendLastRoundDigits), sep='')) | |
} | |
legendLabels = newLegend | |
} | |
legend(legend.loc, legendLabels, col=colours, lty=1, cex=legend.cex) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment