R- spplot not plotting raster stack in gWidgets GUI - r

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:
I produce the plot using a handler within the GUI.
If the plot is produced using a handler within a addHandlerChanged/addHandlerClicked function.
If the plot is loaded to the GUI directly from the R console.
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.
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

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])

Related

Saving raster in R using png() and levelplot results in strange lines

I think I may have discovered a bug. I'm using levelplot in rasterVis, when I plot the rasters they show up fine in the raster window, however when I try and save them using png() the raster has lines through it.
library(raster)
library(rasterVis)
library(RColorBrewer)
col<-rasterTheme(region=brewer.pal(8,"YlOrRd"))
r<-raster(ncol=40,nrow=20)
r[] <- rnorm(n=ncell(r))
b<-"Title"
png(file=paste0(path,"\\",b,".png"), width=1800, height=1800, res=300)
plot<-levelplot(r,main=b,par.settings=col, margin=FALSE, scales=list(draw=FALSE))
print(plot)
dev.off()
In the plot window it shows up as it should:
But saved using png():
I figured it out, the margins parameter needs to be in the form of a list. Resolves the lines in the images.
plot<-levelplot(r,main=b,par.settings=col, margin=list(draw=FALSE,scales=list(draw=FALSE)))

Plotted raster output in R won't eliminate legend margin

In R, I have a raster object generated from a kernel density analysis using the ks package. I convert this into a raster object (from the raster package) and try to draw that raster object to a PNG using plot(). I want the png to have exactly one pixel for every pixel in the raster object. Simple enough, right? By default of course, I get all sorts of extraneous junk added to the plot. I can remove most of this using the various settings in plot() or par(), but no matter what I do, I don't seem able to get rid of the space formerly taken up by the legend on the right side of the plot.
library('ks')
library('raster')
# generate the data
set.seed(1)
x = matrix(rnorm(1000,1,0.5),500)
xpix = 100
ypix = 100
# calculate the density function
k = kde(
x,
H=matrix(c(0.1,0,0,0.1),2),
xmin=c(0,0),
xmax=c(1,1),
gridsize=c(xpix,ypix)
)
# convert to raster
r = raster(k)
# plot the image to PNG
png('file.png',width=xpix,height=ypix)
par(
mar=c(0,0,0,0),
bty='n',
bg='black',
plt=c(0,1,0,1)
)
plot(
r,
legend=FALSE,
axes=FALSE,
plt=c(0,1,0,1)
)
# see that 'plt' did not change
print(par())
dev.off()
If I check par before closing the device, I can see that the 'plt' value is not what I set it to; it shows the right margin, where the plotting area has been nudged over to make space for the non-legend. Sample code is above, and the image it generates is linked to here.
Incidentally, I was able to achieve the correct effect with the image() function instead of plot(), though that introduced it's own problems, namely that transparency no longer worked. Can I solve this with plot()? It's very frustrating that I'm so close but just can't seem to change the size of the plot area! I don't want to use another graphics package if there is any way to make the base function work.

R language: plot grid lines only inside the graph

I am trying to remove all grid lines outside the graph. I noticed that behavior in R is not deterministic, i.e., sometimes grid lines are inside the graph only (as I want), but sometimes it spans an entire figure (see sample). I'd like to always put grid lines inside.
I read grid manual, but could not find an option to do so. abline() also puts grid lines across an entire figure.
The code I am using is
plot(xrange, yrange, type="n", xlab="X", ylab="Y", xlim=c(200,1500), ylim=c(0,10000))
...
grid(lty=3, col="gray")
Any help is appreciated. Thanks,
Nodir
When I have had this problem it is because par(xpd=TRUE) is somewhere in the code. Try setting par(xpd=FALSE) before using grid() and then par(xpd=TRUE). The sample code was used to generate the same the two plots, one of which has the grid lines extending outside of the plot region.
set.seed(1)
x <- rnorm(100)
y <- rnorm(100)
# scatter plot with gridlines inside
par(xpd=FALSE) # do not plot outside the plot region
plot(x,y)
grid(lwd=2)
# scatterplot with gridlines outside the region
par(xpd=TRUE) # plot outside the plot region
plot(x,y)
grid(lwd=2)

"Error in plot.new() : plot region too large" while plotting 4 maps(2*2) inside one layout/faced/grid using R

I am new to R and trying to plot airline network graphs using Map in R.
I am stuck at a point where I want to plot 4 different plots in a panel/ facet/grid. i am getting an error as follows :
Error in plot.new() : plot region too large
Sample Code till now :
get( getOption( "device" ) )()
par( mfrow = c( 2, 2 ) ) // 2 * 2 matrix intended
map("world", col="#191919", fill=TRUE, bg="#111111", lwd=0.05, xlim=xlim, ylim=ylim)
//sample map without any network lines ..
PS : This is not a duplicate post. I saw some posts with figure margins too large in R. But this is something different as per my understanding.
This is a problem linked to RStudio (see here). It occurs when the Plots pane area is smaller than the plot area.
Solutions:
Enlarging the Plots pane (thanks to #Roman Luštrik for the suggestion). However it doesn't always work. Sometimes the plot area is still greater than the Plots pane area, even after increasing it.
Using "raw R" as suggested by #Roman Luštrik (thanks again). It solves the problem completely since R adapts the plot size to the plotting window.
Plotting to a file also solves the problem when using RStudio.
run dev.off() before you plot your data

Save the orientation of a RGL plot3d() plot

I have a 3D plot using RGL. I would like to make identical plots using color to highlight the distribution of some variable. To do this I would like to have identical plots, how do I find and set the orientation of a plot?
Once I make a preliminary plot, I move it around to find a nice display angle and I would like to save that angle and incorporate it into future plotting scripts. Anyone have a suggestion on how to do this?
library(rgl)
plot3d(iris)
#play with the plot to find a good angle
#save the angle for future plots
Ben's comment basically answers your question; this just applies expand.dots to what he wrote ;)
## In an inital session:
library(rgl)
plot3d(iris)
## Now move the image around to an orientation you like
## Save RGL parameters to a list object
pp <- par3d(no.readonly=TRUE)
## Save the list to a text file
dput(pp, file="irisView.R", control = "all")
.......
## Then, in a later session, to recreate the plot just as you had it:
library(rgl)
pp <- dget("irisView.R")
plot3d(iris)
par3d(pp)

Resources