Skip to content

Instantly share code, notes, and snippets.

@CnrLwlss
Created August 18, 2021 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CnrLwlss/095b4e66c64ef57c2ae1284804a5242b to your computer and use it in GitHub Desktop.
Save CnrLwlss/095b4e66c64ef57c2ae1284804a5242b to your computer and use it in GitHub Desktop.
Separating plot rendering from analysis
# 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