I would like to add an enlarged portion of my map to the original map and have as the final product, one map that shows both the original map, and also the enlarged/zoomed portion. Using the meuse dataset as an example:
library(sp)
library(lattice)
data(meuse)
coordinates(meuse)=~x+y
gridded(meuse)<-TRUE
rasters.m<-list()
for (i in 1:12){
rasDF <- raster(meuse, layer=i)
rasters.m[[i]]<-rasDF
}
stack.sp<-stack(rasters.m)
plot(stack.sp) # gives a gridded view of the stacked rasters. But now I would like to zoom in..
zoom.ent<-zoom(stack.sp,1) # The zoomed in portion appears as a new window, with the boundaries of the zoomed area highlighted in red on the original map.
I am not sure if there is a command in the raster or rasterVIS packages that would allow one to add the zoomed in part of the raster onto the original map. I have tried the par function but that doesn't work. Any suggestions would be welcomed.
This is more or less the same question you asked here. For Raster* objects you have to use the shift function. The result can be combined with the +.trellis function of the latticeExtra package:
library(raster)
library(rasterVis)
f <- system.file("external/test.grd", package="raster")
r <- raster(f)
rZoom <- crop(r, extent(180000, 181000, 330000, 331500))
displaced <- shift(rZoom, x = -1200, y = 2000)
levelplot(r) + levelplot(displaced)
Related
I'm trying to crop a large multipolygon shapefile by a single, smaller polygon. It works using st_intersection, however this takes a very long time, so I'm instead trying to convert the multipolygon to a raster, and crop that raster by the smaller polygon.
## packages - sorry if I've missed any!
library(raster)
library(rgdal)
library(fasterize)
library(sf)
## load files
shp1 <- st_read("pathtoshp", crs = 27700) # a large multipolygon shapefile to crop
### image below created using ggplot- ignore the black boundaries!
shp2 <- st_read("pathtoshp", crs = 27700) # a single, smaller polygon shapefile, to crop shp1 by
plot(shp2)
## convert to raster (faster than st_intersection)
projection1 <- CRS('+init=EPSG:27700')
rst_template <- raster(ncols = 1000, nrows = 1000,
crs = projection1,
ext = extent(shp1))
rst_shp1 <- fasterize(shp1, rst_template)
plot(rst_shp1)
rst_shp2 <- crop(rst_shp1, shp2)
plot(rst_shp2)
When I plot shp2, the upper boundary is flat, rather than fitting the true boundary of the shp2 polygon.
Any help would be greatly appreciated!
Maybe try raster::mask() instead of crop(). crop() uses the second argument as an extent with which to crop a raster; i.e. it's taking the bounding box (extent) of your second argument and cropping that entire rectangle from your raster.
Something important to understand about raster objects is that they are all rectangular. The white space you see surrounding your shape are just NA values.
raster::mask() will take your original raster, and a spatial object (raster, sf, etc.) and replace all values in your raster which don't overlap with your spatial object to NA (by default, you can supply other replacement values). Though I will say, mask() will likely also take awhile to run, so you may be better off just sticking with sf objects.
I would suggest moving to the "terra" package (faster and easier to use than "raster").
Here is an example.
library(terra)
r <- rast(system.file("ex/elev.tif", package="terra"))
v <- vect(system.file("ex/lux.shp", package="terra"))[4]
x <- crop(r, v)
plot(x); lines(v)
As edixon1 points out, a raster is always rectangular. If you want to set cells outside of the polygon to NA, you can do
x <- crop(r, v, mask=TRUE)
plot(x); lines(v)
In this example it makes no sense, but you could first rasterize
x <- crop(r, v)
y <- rasterize(v, x)
m <- mask(x, y)
plot(m); lines(v)
I am not sure if this answers your question. But if it does not, then please edit your question to make it reproducible, for example using the example data above.
I am trying to do universal cokriging in R with the Gstat package. I have a script that i was helped with, but now i'm stuck and can't ask assistance from the original source.
The problem is that i can't change the output resolution of the cokriged data. I would like to import the interpolated map to ArcMap and point-to-raster leaves me with a very low resolution.
My script is as follows:
library(raster)
library(gstat)
library(sp)
library(rgdal)
library(FitAR)
Loading my dataset, that containes coordinates and sampled values:
kova<-read.table("katvus_point_modif3.txt",sep=" ",header=T)
coordinates(kova)=~POINT_X+POINT_Y
Loading depth values at the same coordinates as the previous, this is my covariate:
Sygavus<-read.table("sygavus_point_cokrig.txt",sep=" ",header=T)
coordinates(Sygavus)=~POINT_X+POINT_Y
overlay <- over(kova,Sygavus)
kova$Sygavus <- overlay$Sygavus
This is supposed to set the boundary for my interpolation, the file is an exported shapefile from ArcMap:
border <- shapefile("area_2014.shp")
projection(kova)=projection(border)
This is supposed to create a grid for cokriging and the res= should let me specify what resolution i want the output to be, but no matter what number i use the output does not change.
grid <- spsample(border,type="regular",res=25)
I remove overlaping points:
zero <- zerodist(kova)
kova <- kova[-zero[,2],]
I load in the depth covariate raster-file. This is a depth raster export from ArcMap to ascii form:
depth <- raster("htp_depth_covar.asc")
projection(depth)=projection(border)
overlay <- extract(depth,kova)
kova$depth <- overlay
I remove na! values from the overlain depth values (These values should be the same as the previously loaded depth covariate table at the respective coordinates, but if i leave that part out, the script stops functioning)
kova <- kova[!is.na(kova$depth),]
kova.gstat <- gstat(id="Kova",formula=kova~depth,data=kova)
kova.gstat <- gstat(kova.gstat,id="Sygavus",formula=Sygavus~depth,data=kova)
var.kova <- variogram(kova.gstat)
plot(var.kova)
kova.gstat <- gstat(kova.gstat,id=c("Kova","Sygavus"),model=vgm(psill=cov(kova$kova,kova$Sygavus),model="Mat",range=12000,nugget=0))
kova.gstat <- fit.lmc(var.kova,kova.gstat,model=vgm(psill=cov(kova$kova,kova$Sygavus),model="Mat",range=12000,nugget=0))
plot(var.kova,kova.gstat$model)
overlay <- extract(depth,grid)
grid <- as.data.frame(grid)
grid$depth <- overlay
coordinates(grid)=~x1+x2
projection(grid)=projection(border)
krige <- predict.gstat(kova.gstat,grid)
spplot(krige,c("Kova.pred"))
write.table(krige, "kova.raster1.ck.csv", sep=";", dec=",", row.names=F)
Any help in understanding the gstat cokriging and the script overall would be greatly appreciated!
Because you don't provide a reproducible example I can only guess, but I think that spsample ignores the res=25 argument. Try n=1000 instead and then increase that value to get higher resolution.
I have a raster in an equal area Behrmann projection and I would like to project it to the Mollweide projection and plot.
When I do this with the following code, however, the plotting doesn't seem right, as the map extends to the sides, and there are outlines of various landmasses where I wouldn't expect them.Also, the map extends beyond the plot window.
Can anyone please help me get this to plot nicely?
Thanks!
The data file used can be downloaded from this link.
Here is the code I have so far:
require(rgdal)
require(maptools)
require(raster)
data(wrld_simpl)
mollCRS <- CRS('+proj=moll')
behrmannCRS <- CRS('+proj=cea +lat_ts=30')
sst <- raster("~/Dropbox/Public/sst.tif", crs=behrmannCRS)
sst_moll <- projectRaster(sst, crs=mollCRS)
wrld <- spTransform(wrld_simpl, mollCRS)
plot(sst_moll)
plot(wrld, add=TRUE)
Alright, since the example at this page seems to work, I tried to mimic it as much as possible. I think problems arise because the far left and far right side of the raster image overlap. Cropping and an intermediate reprojection to Lat-Lon as in the example seem to solve your problem.
Perhaps this workaround can be a basis for a more elegant solution that directly addresses the problem, as it is not benificial to reproject a raster twice.
# packages
library(rgdal)
library(maptools)
library(raster)
# define projections
mollCRS <- CRS('+proj=moll')
behrmannCRS <- CRS('+proj=cea +lat_ts=30')
# read data
data(wrld_simpl)
sst <- raster("~/Downloads/sst.tif", crs=behrmannCRS)
# crop sst to extent of world to avoid overlap on the seam
world_ext = projectExtent(wrld_simpl, crs = behrmannCRS)
sst_crop = crop(x = sst, y=world_ext, snap='in')
# convert sst to longlat (similar to test file)
# somehow this gets rid of the unwanted pixels outside the ellipse
sst_longlat = projectRaster(sst_crop, crs = ('+proj=longlat'))
# then convert to mollweide
sst_moll <- projectRaster(sst_longlat, crs=mollCRS, over=T)
wrld <- spTransform(wrld_simpl, mollCRS)
# plot results
plot(sst_moll)
plot(wrld, add=TRUE)
I have a raster object to which I would like to add points.
However, when I change plot size, by making it full screen for example, the points change their positions.
Is there a way to give them exact positions, independent of plot size?
reproducable code:
r<- raster(nrows=10, ncols=10)
r <- setValues(r, 1:ncell(r))
plot(r)
points(x=-50,y=20)
points(x=-50,y=-90)
I'm not allowed to post images. But the lower point gets out of the coloured region when I make the device smaller or moves more into the coloured region when I make the device bigger.
Cheers
this problem has been exposed here too: plotting spatial points over a raster layer in r.
I tried to overpass it by creating a SpatialPointsDataFrame:
r<- raster(nrows=10, ncols=10)
r <- setValues(r, 1:ncell(r))
plot(r)
points(x=-50,y=20)
points(x=-50,y=-90)
coor1<- data.frame(Lat=-50,Lon=20)
point1 <- SpatialPointsDataFrame(
data.frame(coor1$Lon,coor1$Lat),
data.frame('Landriano')
)
x11()
plot(r)
plot(point1, add=T)
The only solution I see is once you overlap the point over the raster you shouldn't change the plot window size. Otherwise the points will be shifted somewhere randomly...
As the title says I am trying to plot a polygons using the PlotPolysonStaticMap function in RgoogleMaps. My polygon is a subset from a larger dataset of World Wildlife Fund (WWF) ecoregions. Since the bounds of my ecoregion confine the bounds of another ecoregion there should be a "hole" or a blank space in the midst of my polygons. When I plot the shapefile using the plot function the hole appears as white. When I plot the polygon over the base map from RgoogleMaps the hole appears in color and I do not know how to change this.
The full map is available here. It needs to be downloaded and unzipped for my code to work.
library(rgdal)
library(RgoogleMaps)
library(PBSmapping)
WWF<-readOGR(dsn="wwf_terr_eco.shp",layer="wwf_terr_eco"
ACADIA<-WWF[WWF#data$ECO_NAME%in%c("New England-Acadian forests"),]
ACADIA <- SpatialPolygons(ACADIA#polygons,proj4string=ACADIA#proj4string)
add.alpha <- function(col, alpha=1){
if(missing(col))
stop("Please provide a vector of colours.")
apply(sapply(col, col2rgb)/255, 2,
function(x)
rgb(x[1], x[2], x[3], alpha=alpha))
}
mycol=add.alpha("#507415",alpha=.4)
terrMap<-GetMap(center=c(46,-66.8),zoom=6,maptype="terrain")
PlotOnStaticMap(terrMap)
PlotPolysOnStaticMap(terrMap, ACADIA_ONLY,col =mycol ,border = NULL, lwd = 0.25,
verbose = T)
Thanks!
I do not know well RgoogleMaps package (the error seems come from the function PlotPolysOnStaticMap behavior with complex polygons), so I can't answer your question precisely, but I you with an other way you can play with OpenStreetMap.
library(rgdal)
library(OpenStreetMap)
WWF<-readOGR(dsn="/home/delaye/Téléchargements/official/",layer="wwf_terr_ecos")
ACADIA<-WWF[WWF#data$ECO_NAME%in%c("New England-Acadian forests"),]
##reprojection with osm system
ACADIA<-spTransform(ACADIA,osm())
##alpha definition
add.alpha <- function(col, alpha=1){
if(missing(col))
stop("Please provide a vector of colours.")
apply(sapply(col, col2rgb)/255, 2,
function(x)
rgb(x[1], x[2], x[3], alpha=alpha))
}
mycol=add.alpha("#507415",alpha=.4)
##load data from osm (you can play with type='bing' to)
map.osm<-openmap(c(49.849184,-75.214844),c(42.013233,-59.877930),type="osm")
plot(map.osm)
##add you datalayer on the plot
plot(ACADIA,add=T,col=mycol)
and the result is
I hope it can help