Created
August 18, 2021 11:52
-
-
Save CnrLwlss/095b4e66c64ef57c2ae1284804a5242b to your computer and use it in GitHub Desktop.
Separating plot rendering from analysis
This file contains 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
# How to separate plotting from CPU intensive analysis | |
plotfuns = list() | |
Npts = 1000 | |
Nsims = 12 | |
# Visualising a 1D random walk, for example | |
makewalk = function(Npts){ | |
# Do some like real heavy computing man | |
deltas = sample(c(-1,1),Npts,replace=TRUE) | |
walk = cumsum(deltas) | |
# Return a new function DEFINITION without executing plotwalk function | |
return(list("plotter"=function() plotwalk(walk),"walk"=walk)) | |
} | |
plotwalk = function(walk) { | |
mlab = paste0("Random Walk ",sprintf("%04d", i)) | |
plot(walk,type="s",xlab="Time (ms)",ylab="Position (mm)",cex.lab=1.54,main=mlab) | |
} | |
for(i in 1:Nsims){ | |
# Without actually executing the plotwalk function, store its output inside another function in e.g. a list | |
plotfuns[[i]] = makewalk(Npts)[["plotter"]] | |
} | |
# Now we have a list of functions, which we can execute to make the plots in whatever format we like | |
# One plot per page | |
pdf("RandomWalkPages.pdf") | |
for(i in 1:Nsims) walk = plotfuns[[i]]() | |
dev.off() | |
# Four plots per page | |
pdf("RandomWalkArrays.pdf") | |
op = par(mfrow=c(2,2),mai=c(0.75,0.75,0.5,0.5)) | |
for(i in 1:Nsims) walk = plotfuns[[i]]() | |
par(op) | |
dev.off() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment