How can i use "rasterVis" package to overlay two raster and display well? - r

I want to overlay two raster objects.
I asked the question(Raster overlay visualization in rasterVis package: How the Significant raster images are represented as point marks?).
I refer to the #thiagoveloso'answer from this(Adding stippling to image/contour plot).
But the display is not what I wanted. It's not obvious and beautiful. If I try to change the shape or size of the mark, it will take a long long long time to draw or become weird.
Here is my code:
library(raster)
library(rasterVis)
rm(list = ls())
MK<-raster("C:/e_Zs——trend.tif")
### MK<1.96 set value to NA
fun <- function(x) { x[x<3] <- NA; return(x) }
MK<-calc(MK,fun = fun)
## load trend
Trend<- raster("C:/e_slope_trend.tif")
# And this is the key step:
# Converting the "mask" raster to spatial points
r.mask <- rasterToPoints(MK, spatial=TRUE)
plot(r.mask,cex=0.01)
# Plot
levelplot(Trend, margin=NA,par.settings=RdBuTheme) +
latticeExtra::layer(sp.points(r.mask, pch=100, cex=0.1, alpha=0.3,col="Black"))
I want to draw a fig,like:
And the fig like:
If i change the cex=0.5,it will lke:
If I change the shape of the mark, it will do so long... So. get any idea?

Related

Represent a colored polygon in ggplot2

I am using the statspat package because I am working on spatial patterns.
I would like to do in ggplot and with colors instead of numbers (because it is not too readable),
the following graph, produced with the plot.quadratest function: Polygone
The numbers that interest me for the intensity of the colors are those at the bottom of each box.
The test object contains the following data:
Test object
I have looked at the help of the function, as well as the code of the function but I still cannot manage it.
Ideally I would like my final figure to look like this (maybe not with the same colors haha):
Final object
Thanks in advance for your help.
Please provide a reproducible example in the future.
The package reprex may be very helpful.
To use ggplot2 for this my best bet would be to convert
spatstat objects to sf and do the plotting that way,
but it may take some time. If you are willing to use base
graphics and spatstat you could do something like:
library(spatstat)
# Data (using a built-in dataset):
X <- unmark(chorley)
plot(X, main = "")
# Test:
test <- quadrat.test(X, nx = 4)
# Default plot:
plot(test, main = "")
# Extract the the `quadratcount` object (regions with observed counts):
counts <- attr(test, "quadratcount")
# Convert to `tess` (raw regions with no numbers)
regions <- as.tess(counts)
# Add residuals as marks to the tessellation:
marks(regions) <- test$residuals
# Plot regions with marks as colors:
plot(regions, do.col = TRUE, main = "")

Reduce file size of a plot (R) (plotly)

I've created a map in R using ggplotly. To create a link, it needs to be 524kb or under, but it currently is 1.2Mb. Are there any good ways of reducing file size so I can export it? Or is this totally unrealistic?
If your map has polygons, consider rmapshader::ms_simplify(), which uses the Visvalingam algorithm to reduce the number of points used to construct a polygon.
Here's a reproducible example:
> p <- raster::shapefile(system.file("external/lux.shp", package="raster")) # load data
> p2 <- rmapshaper::ms_simplify(p, keep_shapes = TRUE) # simplify polygons
Now visualize the result:
> par(mfrow = c(1,2))
> plot(p, main = paste("before:", object.size(p), "bytes"))
> plot(p2, main = paste("after:", object.size(p2), "bytes"))
> dev.off()
You can edit the default settings on the keep argument, lowering the number of points to retain, and thus further reducing your object size. This comes at the cost of a coarser image.

Using a raster attribute from a multi-attribute raster for colour levels in a plot in R

I have a raster object with a large number of attributes, and I would like to plot the spatial data in R and colour code it by a certain attribute. I have not been able to work out how to use the information of a particular attribute to achieve this. So far I have successfully extracted the attribute of choice using factorValues(), but I cannot determine how to now incorporate this information into the plot() function. I tried using the ratify() and level() functions mentioned in the raster package documentation, but I don’t understand how the simplified online examples can be adapted for a raster with multiple attributes.
Any advice on how to achieve this would be greatly appreciated.
# read in shapefile
shp = readOGR(".", "grid")
#convert to raster
r = raster(extent(shp))
res(r) = c(1,0.5)
ra = rasterize(shp, r)
#crop raster to desired extent
rcrop = crop(ra, extent(-12, 2, 29, 51))
# extract attribute value of interest
f = factorValues(rcrop, 1:420, layer=1, att=17, append.names=FALSE)
# here there are 420 cells in the raster and I am interested in plotting values of attribute 17 of the raster (this is currently a numeric attribute, not a factor)
#extra code to set attribute as the level to use for plotting colours???
rcrop = ratify(rcrop)
rat = levels(rcrop)[[1]] #this just extras row IDs..not what I want
#…
### plot: I want to plot the grid using 7 colours (I would ideally like to specify the breaks myself)
require(RColorBrewer)
cols = brewer.pal(7,"YlGnBu")
#set breaks
brks = seq(min(minValue(rcrop)),max(maxValue(rcrop),7))
#plot
plot(rcrop, breaks=brks, col=cols, axis.arg=arg)
The following is pretty hacky (and may perform poorly for large rasters), but I'm not sure if there's a way to link col.regions to a specified attribute.
rasterVis::levelplot does a nice job of labelling colour ramps corresponding to factor rasters, and while it provides an att argument allowing you to specify which attribute you're interested in, this seems to only modify the labelling of the ramp. Raster cell values control how the colour ramp is mapped to the raster, so it seems to me that we need to modify the cell values themselves. Maybe #OscarPerpiñán will chime in here to prove me wrong :)
We can create a simple function to substitute the original cell values with whichever attribute we want:
switch_att <- function(r, att) {
r[] <- levels(r)[[1]][values(r), att]
r
}
Let's download and import a small example polygon dataset from Natural Earth:
library(rasterVis)
library(rgdal)
require(RColorBrewer)
download.file(file.path('http://www.naturalearthdata.com',
'http//www.naturalearthdata.com/download/110m/cultural',
'ne_110m_admin_0_countries.zip'),
f <- tempfile())
unzip(f, exdir=tempdir())
shp <- readOGR(tempdir(), 'ne_110m_admin_0_countries')
rasterize the vector data:
r <- rasterize(shp, raster(raster(extent(shp), res=c(1, 1))))
And create some plots with levelplot:
levelplot(switch_att(r, 'continent'), col.regions=brewer.pal(8, 'Set2')) +
layer(sp.polygons(shp, lwd=0.5))
levelplot(switch_att(r, 'economy'), par.settings=BuRdTheme) +
layer(sp.polygons(shp, lwd=0.5))
EDIT
With Oscar's update to rasterVis, the switch_att hack above is no longer necessary.
devtools::install_github('oscarperpinan/rastervis')
levelplot(r, att='continent', col.regions=brewer.pal(8, 'Set2')) +
layer(sp.polygons(shp, lwd=0.5))
will produce the same figure as the first one above.

How to plot additional raster with spplot?

I want to plot SpatialPolygonsDataFrame as a semi-transparent main object (with legend on the right), but I want to plot yet additional raster (hillshade) as a background - just to make nicer map. I would need something like:
spplot(polygons, sp.layout = list(list("raster", myRaster)))
but looking at ?spplot, it doesn't seem to be possible to specify the raster in sp.layout. I can't specify the raster as the main object, because the main object are the polygons dataFrame, whose value scale I want to plot in the legend on the right side.
How is it possible to plot an additional raster in spplot?
Here's one way to do it. There's probably a neater way to achieve it without plotting the polygon object twice, though...
library(sp)
library(rasterVis)
r <- raster(nrow=18, ncol=36)
r[] <- runif(ncell(r)) * 10
r[r > 8] <- NA
pol <- rasterToPolygons(r, function(x) x > 6)
spplot(pol) + levelplot(r) + spplot(pol)
Or alternatively:
library(latticeExtra)
spplot(pol) + spplot(r) + spplot(pol)
EDIT
As per the comment by #OscarPerpiñán, a better way to do this is:
spplot(pol) + as.layer(spplot(r), under = TRUE)

How to plot and animate coordinates (latitude/longitude) data in R?

I have 10 lat and long points. With the code below, I can plot the coordinates, draw arrows in the order of their sequence and out-put a gif file that shows navigation order.
So far I was able to do this only with plot {graphics} function. because arrow {graphics} and saveGIF{animation} only seems to work with the plot function. I am wondering if its possible to this a more appropriate library such as ggmap (edit: I had mistakenly said ggplot), googleVis and etc.
library(graphics)
library(animation)
lat <- c(34.083398,34.072467,34.030237,34.597334,34.587142,34.488386,33.443484,33.946902,33.062739,32.273711,32.272611)
lon <- c(-107.907107,-106.893156,-107.971542,-105.225107,-105.13397,-103.196355,-104.52479,-103.655698,-106.0156,-107.71744,-107.713977)
coords = data.frame(lat,lon)
x <- coords$lat ; y <- coords$lon
s <- seq(length(x)-1) # one shorter than data
saveGIF({
for(s in 1:length(x)){
plot(x,y)
arrows(x[s], y[s], x[s+1], y[s+1], col = 1:s)
}
})
Yes, just remember to wrap your ggplot calls in print so they produce output. Toy example:
data=data.frame(i=1:100,x=runif(100),y=runif(100))
saveGIF({for(i in 2:100){print(ggplot(data[1:i,],aes(x=x,y=y))+geom_point())}})
Just write your code to produce each frame with ggplot2 functions and wrap in print. What did you try?

Resources