resizing plot output causes raster and points to become misaligned [duplicate] - r

This question already has answers here:
ploting artefact with points over raster
(2 answers)
Closed 8 years ago.
If I use plot() to draw a GIS raster image, then use points() to add some points on the image: E.g. the following code
in_rast_str <- "PET_eclp.tif"
in_rast <- raster(in_rast_str)
selected_cells <- choose_points(in_rast_str,10,30)
plot(in_rast)
points(selected_cells[,1],selected_cells[,2])
The initial output renders correctly. However, if I then resize the plot either in the export window, or in the zoom window of RStudio, the points and the underlying raster shift relative to each other and become misaligned.
Is this a problem with RStudio or with R?
I'm guessing that this could be a bug rather than that I am doing something obviously wrong.
Update...
Here are some examples:
and the same plot, but resized

That issue with raster has been annoying me for years.
This doesn't exactly answer your question, but rasterVis provides a very pleasing (to me, anyway) workaround.
library(rasterVis)
r <- raster(matrix(runif(100), 10))
xy <- xyFromCell(r, which(values(r) > 0.9))
levelplot(r, margin=FALSE) + layer(sp.points(xy, pch=20, cex=2, col=1))
Resize and zoom around as much as you like - the points will stick to the correct cells.

Related

How to set ylim and xlim in plot raster in R

I'm making a raster data ploting in R, when I adjust to the area I'm working on, R displays the ylim that doesn't want to be cut off.
I tried:
# set lon lat
ylim=c(-4,2)
xlim=c(118,126)
plot(pm10_mean,xlim=xlim, ylim=ylim)
plot(shp, add=TRUE)
plot(shp2, add=TRUE)
but I got picture like this
How to remove free space above 2 and below -4? I just want to plot area in xlim and ylim
I think spplot works fine but I find it really slow and hard to customize.
I found a more recent duplicate of this question in gis.stackexchange and provided the below answer:
I found that raster::plot's documentation indicates that you can specify the plotting window and in my experience it has zero effect. Instead it will always assume the extent of the raster you give it.
My suggested workaround is to first draw your desired plot window with a blank object then add the raster plot to this window.
my_window <- extent(-4, 2, 118, 126)
plot(my_window, col=NA)
plot(my_raster, add=T)
For me, this achieves what I'm after. The caveat is if you're plotting a stack or brick, the add functionality doesn't work in my experience. The solution is to use subset, like plot(subset(my_brick,4), add=T)
I have had this problem before. You can manually resize the plot area to remove the blank areas, or insert polygons to cover the unwanted areas of shapefile. But the safest option is to use spplot as this will automatically resize the plotting area for you:
require(maptoolS)
require(raster)
data(wrld_simpl)
rs=raster()
rs[]=1
id_shp=wrld_simpl[which(wrld_simpl$ISO2=="ID"),]
rs=crop(rs,id_shp)
rs=disaggregate(rs,40)
rs=mask(rs,id_shp)
spplot(rs,ylim=c(-4,2),xlim=c(118,126),sp.layout=list('sp.lines', id_shp, lwd=2,first=F))
Just as easy to simply plot a NULL plot and add your raster
plot(NULL, xlim = c(-114.5, -35.5), ylim = c(-24.5, 29.5), asp = 30/30,
xlab = "Longitude", ylab = "Latitude")
plot(your_raster, add = T)
Stacking still seems to work

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.

ggplot2 - making a stick plot (plotting a mass spectrum) [duplicate]

This question already has an answer here:
Needle plot in ggplot2 [duplicate]
(1 answer)
Closed 8 years ago.
I am trying to make a plot x,y stick plot (like the link in the bottom of the post). I am attempting to make a Mass spectrum plot (basically a stick plot), is there an easy way of doing this with ggplot2? I know how to make the plot with the plot() function in R, however, I would like to be able to make it with ggplot 2, as I need to do some additional modifications afterwards for which I require ggplot2.
So essentially I want to make a x,y stick plot. I am new to R, so bear with me.
Example of what I want
Try to upload some code and let us know where you are getting stuck. Also, please refer to the documentation or these examples.
That having been said, I believe this is close to what you want:
library(ggplot2)
ggplot(data = mtcars, aes(x = mpg)) +
geom_bar(binwidth = 1, color = 'white')

suppress the margin of R plots vertically [duplicate]

This question already has answers here:
move subplots closer together with R
(2 answers)
Closed 9 years ago.
I am using base R plot function to generate vertically aligned plots (2-by-1), with both x and y labels but without a title. However, when I use
par(mfrow=c(2,1))
plot(obj1)
plot(obj2)
I notice that the blank margin area between the two plots is so huge (I assume R does not exclude the area for the main= title...). Is there a way to make the two plots more "closer" to each other, while keep the x-labels at appropriate locations?
BTW, is there a way to generate a plot in PDF format without any useless blank margins? I plan to include the figure in the paper manuscript, and I don't want to see such margins occupying. Thanks!
As described in the (duplicate) question I linked to, the solution is exactly the same as there:
par(mfrow=c(2,1))
par(mar = c(0,4,4,2) + 0.1)
plot(1:5)
par(mar = c(5,4,0,2) + 0.1)
plot(1:5)

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