R- spplot not plotting raster stack in gWidgets GUI

350 Views Asked by At

I have been building a small GUI for climate analysis using gWidgets in R. Progress has been slow but steady until I hit a problem trying to display my raster stack of results using spplot(). The issue is that only the first raster in the stack is plotted and the rest are not. This issue occurs regardless if:

  1. I produce the plot using a handler within the GUI.

  2. If the plot is produced using a handler within a addHandlerChanged/addHandlerClicked function.

  3. If the plot is loaded to the GUI directly from the R console.

  4. As above but using using levelplot().

If plot() is used, results are displayed correctly but only the first 16 are displayed (I have 24 graphs) and the scales are not merged producing difficulty in interpreting the results.

Here is some example code to illustrate the issue:

require(gWidgets)
require(raster)

## create example GUI plot area
win = gwindow("Graph test")
nb = gnotebook(container=win,expand=T)
plots = ggraphicsnotebook(container=nb)

## create raster stack
rs=list()
for(i in 1:24){
  rs1=raster()
  rs1[]=rnorm(3600)
  rs[i]=rs1
}
rs=stack(rs)

## attempt to plot stack
spplot(rs) ##plot is not produced correctly with only the first raster plotted

##compare this to plotting in a normal window
windows()
spplot(rs)


Here is an example of the expected plot (left) and the actual (right) using the above code.
Expected and actual results
If anybody has any ideas how to get around this or any alternative plotting options for raster stacks I would love to hear them.

(please note that similar results are produced if I open a separate window using windows() within the GUI or if I use levelplot())

Cheers

1

There are 1 best solutions below

1
On

To those who may be interested. After 3.5 years and a many trials, including recordPlot(), the gridGraphics package and imager::capture.plot(), the only solution that I found was to save the graph as an image and then plot it in the window using rasterImage()

require(gWidgets)
require(gWidgetsRGtk2)
require(RGtk2)
require(raster)
require(png)

options(guiToolkit="RGtk2") 

## create raster stack
rs=list()
for(i in 1:24){
  rs1=raster(nrow=2,ncol=2)
  rs1[]=rnorm(4)
  rs[i]=rs1
}
rs=stack(rs)

##save plot as png
png("out.png")
spplot(rs)
dev.off()
img = readPNG("out.png")


## create example GUI plot area
win = gwindow("Graph test")
nb = gnotebook(container=win,expand=T)
plots = ggraphicsnotebook(container=nb)

##plot
par(mar=rep(0,4))
plot(1, type="n", axes=F, xlab="", ylab="")
usr = par("usr")    
rasterImage(img, usr[1], usr[3], usr[2], usr[4])

enter image description here