My first question here.
I would like to plot three layers of colors in a loop and this is my code:
matx<-array(rep(1:100,100),dim=c(100,100)) #Matrix of horizontal plot values
maty<-array(rep(1:100,each=100),dim=c(100,100)) #Matrix of vertical plot values
colPlant<-array("darkgreen",dim=c(100,100)) #Matrix for plants
colHerbivores<-array(NA,dim=c(100,100)) #Matrix for herbivores
colPredator<-array(NA,dim=c(100,100)) #Matrix for predators
#Start simulation
for(i in 1:20) {
plot(maty~matx,cex=10,pch=".",col=colPlant) #1st layer
points(maty~matx,cex=8,pch=".",col=colHerbivores) #2nd layer
points(maty~matx,cex=6,pch=".",col=colPredator) #3rd layer
colHerbivores[sample(1:10000,10)]<-"orange"
colPredator[sample(1:10000,3)]<-"black"
}
maty and matx contain y-values and x-values (100 * 100 cells). As you can see, I just plot a dot on each position of the 100*100 grid and let the colors match the information in the three matrices.
Plotting the first layer results in a graphics device that has 100*100 green pixels, exactly what I want. The cex value is such that there is no white space between the dots (if bg="white"). The second layer is mainly transparent, but adds some smaller orange pixels to the "field". The third layer in turn is also mainly transparent, but adds some smaller black spots to the "field". This is a very simplified version of my code.
Basically, I plot the plants first and use smaller symbols to overlay the higher trophic levels. I overlay using NA values for positions that are empty, generating transparent color.
Then follows a code changing the number of colored pixels in colHerbivores and colPredator. After the calculations, I want to plot again. My problem is that plotting each layer takes time. Relatively long compared to the calculations. The result is that the 1st layer is visible for a fraction of a second, the 2nd layer is added and then the 3rd, but the user hardly has time to actually see the 3rd layer, because plotting the 1st layer in the next iteration follows too quickly after plotting the 3rd layer in the current interation. This results in 'flickering' of colHerbivores and colPredator with colPlant as background.
I would like to see all trophic levels at once, i.e. the complete image of iteration 1 followed by the complete image of iteration 2 and so on. So, only a single image per iteration. My question: How do I do this?
I have played with exporting the plot as an image using png()
and readPNG
. This converts the complete plot to an image and then plots the image on the graphic device rather than using plot()
, but this considerably slows down the iteration process.
I want to be able to adjust each matrix separately, so combining the three matrices into one is not an option for the calculations.
Does anyone have sugguestions on how to make the trophic levels appear (close to) simultaneously, while keeping the iteration speed?