Using tmap in R shows black background for masked RGB raster - r

I'm attempting to create a map in R using library(tmap) with a full-color RGB, masked Landsat image. The NAs however appear as black. Here's what I did.
Using library(sf) I calculated the centroids of 5 polygons and buffered them by 5000m. Following this I used library(raster) to mask a Landsat image by the buffered centroids. The code looks like this and works perfectly.
# Read in the data
polys <- st_read("nybb.shp")
rast <- brick("LC08_L1TP_013032_20171027_20171027_01_RT.tif")
# Transform polys, crop raster, calculate centroids
polys <- st_transform(polys, crs = crs(rast, asText = TRUE))
rast <- crop(rast, as(polys, "Spatial"))
cent <- st_centroid(polys) %>% st_buffer(., 5000) %>% as(., "Spatial")
# Mask the raster using buffered centroids
r <- mask(rast, cent)
I can accomplish what I want using base R and library(raster) -- BUT I would prefer to do this using tmap.
# Code that works
plot(polys$geometry, col = "grey", border = "white")
plotRGB(r, bgalpha = 0, add = TRUE)
# Code that does not work
# The NAs in the masked raster appear as black
# even when using the colorNA argument
tm_shape(polys) + tm_polygons() +
tm_shape(r, bbox = polys) +
tm_rgb(colorNA = "red")
Any idea how to show the masked raster using tmap's tm_rgb() function without showing the NAs as black?

To create a basemap with tmap, you can use the read_osm function, from the tmaptools package as follows. Note that you must first transform the data into a geographical CRS: epsg=4326
library(tmaptools)
library(OpenStreetMap)
rast <-projectRaster(rast,crs="+init=epsg:4326",method = "ngb") #(you can use method=method="bilinear")
polys <- spTransform(polys, CRS("+init=epsg:4326"))
background <- read_osm(bbox(rast))
tm_shape(background) + tm_raster() +
tm_shape(polys) + tm_polygons() +
tm_shape(r, bbox = polys) +
tm_rgb(colorNA = "red")

Related

Spatial data overlay selection in R

I'm trying to overlay some spatial data from a bigger SpatialPolygonsDataFrame (world size) to a smaller (country size), by doing these:
x <- c("rgdal", "dplyr",'ggplot2')
apply(x, library, character.only = TRUE)
est<-readOGR(dsn='/estados_2010',layer='estados_2010')
est_f<-fortify(est)
est$id<-row.names(est)
est_f<-left_join(est_f,est#data)
zon<-readOGR(dsn='/Zonas Homogeneas/gyga_ed_poly.shp',layer='gyga_ed_poly')
zon_f<-fortify(zon)
zon$id<-row.names(zon)
zon_f<-left_join(zon_f,zon#data)
t<-ggplot()+geom_polygon(data=zon_f,aes(x=long,y=lat,group=group,fill=GRID_CODE))
t+geom_polygon(data=est_f,aes(x=long,y=lat,group=group),fill=NA,color='red')+coord_fixed(xlim=est_f$long,ylim=est_f$lat,1)
Which is resulting in this:
I'm want to select only what is being plotted inside the polygon with the red lines.
If someone could help me with this issue, I'll appreciate
PS.: For those who want to reproduce the example completely by yourselves, the files are available in the links above to my google drive:
https://drive.google.com/open?id=0B6XKeXRlyyTDakx2cmJORlZqNUE
Thanks in advance.
Since you are using polygons to display the raster values, you can use a spatial selection via [ like in this reproducible example:
library(raster)
library(rgdal)
bra <- getData("GADM", country = "BRA", level = 1)
r <- getData("worldclim", res = 10, var = "bio")
r <- r[[1]]
r <- crop(r, bra)
r <- rasterToPolygons(r)
# bra and raster (now as polygons) have to have the same projection, thusly reproject!
bra <- spTransform(bra, CRSobj = proj4string(r))
here comes the magic!!
r <- r[bra, ]
let's look at the results:
library(ggplot2)
t <- ggplot()+
geom_polygon(data=r,aes(x=long,y=lat,group=group, fill = rep(r$bio1, each = 5)))
t +
geom_polygon(data=bra,aes(x=long,y=lat,group=group),fill=NA,color='red') + coord_map()

Change the background color of the added shape file in rasterVis levelplot

I want to change the oceans color (outside of the shapefile boundry). I can clip the raster and change the background color, but here I want to do that with the added shapefile.
library(raster)
library(rasterVis)
library(maps)
library(maptools)
library(mapdata)
r <- raster(nrow=361, ncol=576, ymn=-90, ymx=90)
values(r) <- 1:ncell(r)
data(wrld_simpl, package = "maptools")
levelplot(r)+ layer(sp.polygons(wrld_simpl, lwd=0.1, col='gray'))
First, mask the Raster with the SpatialPolygons object. Cells not covered
by it are set to NA.
land <- mask(r, wrld_simpl)
Now, change the background color (used for the NA cells):
catTheme <- rasterTheme(panel.background = list(col='lightskyblue1'))
And finally, display the result:
levelplot(land, par.settings = catTheme) +
layer(sp.polygons(wrld_simpl,
lwd=0.1, col='gray'))

Transform CircleRange in SpatialPolygon in R

A very common procedure is to transform lines and borders into SpatialPolygons objects using the Polygon functions from the sp package. But is it possible to transform other object classes into SpatialPolygons? I use the function circles from dismo to create a circumference with specific radius distance from a known spatial point. This function returns an object of class CirclesRange.
circ<-circles(spcoords,d=100000)
class(circ)
[1] "CirclesRange"
attr(,"package")
[1] "dismo"
When I try to convert the CirclesRange object into SpatialPolygons, the following error occurs:
Error: is.integer(pO) is not TRUE
Then, I have searched other ways to transform this object, but I have not been successful. I think that first it is necessary to transform "circ" into another class and then try to convert it to SpatialPolygons, but I can't find information about this.
Have a look at str(circ), the desired SpatialPolygons object is already part of the created object. You simply need to run circ#polygons to extract the polygon. Here is some sample code based on the meuse dataset.
## sample data
data(meuse)
coordinates(meuse) <- ~ x + y
proj4string(meuse) <- CRS("+init=epsg:28992")
## circle around the first 'meuse' feature (top-right corner)
circ <- circles(meuse[1, ], d = 1000, lonlat = FALSE)
poly <- circ#polygons
proj4string(poly) <- proj4string(meuse)
## display data
library(latticeExtra)
spplot(meuse, "elev", scales = list(draw = TRUE),
col.regions = topo.colors(100), key.space = "right") +
as.layer(spplot(poly, fill = "transparent", lwd = 2))

Overlap image plot on a Google Map background in R

I'm trying to add this plot of a function defined on Veneto (italian region)
obtained by an image and contour:
image(X,Y,evalmati,col=heat.colors(100), xlab="", ylab="", asp=1,zlim=zlimits,main=title)
contour(X,Y,evalmati,add=T)
(here you can find objects: https://dl.dropboxusercontent.com/u/47720440/bounty.RData)
on a Google Map background.
I tried two ways:
PACKAGE RGoogleMaps
I downloaded the map mbackground
MapVeneto<-GetMap.bbox(lonR=c(10.53,13.18),latR=c(44.7,46.76),size = c(640,640),MINIMUMSIZE=TRUE)
PlotOnStaticMap(MapVeneto)
but i don't know the commands useful to add the plot defined by image and contour to the map
PACKAGE loa
I tried this way:
lat.loa<-NULL
lon.loa<-NULL
z.loa<-NULL
nx=dim(evalmati)[1]
ny=dim(evalmati)[2]
for (i in 1:nx)
{
for (j in 1:ny)
{
if(!is.na(evalmati[i,j]))
{
lon.loa<-c(lon.loa,X[i])
lat.loa<-c(lat.loa,Y[j])
z.loa<-c(z.loa,evalmati[i,j])
}
}
}
GoogleMap(z.loa ~ lat.loa*lon.loa,col.regions=c("red","yellow"),labels=TRUE,contour=TRUE,alpha.regions=list(alpha=.5, alpha=.5),panel=panel.contourplot)
but the plot wasn't like the first one:
in the legend of this plot I have 7 colors, and the plot use only these values. image plot is more accurate.
How can I add image plot to GoogleMaps background?
If the use of a GoogleMap map is not mandatory (e.g. if you only need to visualize the coastline + some depth/altitude information on the map), you could use the package marmap to do what you want. Please note that you will need to install the latest development version of marmap available on github to use readGEBCO.bathy() since the format of the files generated when downloading GEBCO files has been altered recently. The data from the NOAA servers is fine but not very accurate in your region of interest (only one minute resolution vs half a minute for GEBCO). Here is the data from GEBCO I used to produce the map : GEBCO file
library(marmap)
# Get hypsometric and bathymetric data from either NOAA or GEBCO servers
# bath <- getNOAA.bathy(lon1=10, lon2=14, lat1=44, lat2=47, res=1, keep=TRUE)
bath <- readGEBCO.bathy("GEBCO_2014_2D_10.0_44.0_14.0_47.0.nc")
# Create color palettes for sea and land
blues <- c("lightsteelblue4", "lightsteelblue3", "lightsteelblue2", "lightsteelblue1")
greys <- c(grey(0.6), grey(0.93), grey(0.99))
# Plot the hypsometric/bathymetric map
plot(bath, land=T, im=T, lwd=.03, bpal = list(c(0, max(bath), greys), c(min(bath), 0, blues)))
plot(bath, n=1, add=T, lwd=.5) # Add coastline
# Transform your data into a bathy object
rownames(evalmati) <- X
colnames(evalmati) <- Y
class(evalmati) <- "bathy"
# Overlay evalmati on the map
plot(evalmati, land=T, im=T, lwd=.1, bpal=col2alpha(heat.colors(100),.7), add=T, drawlabels=TRUE) # use deep= shallow= step= to adjust contour lines
plot(outline.buffer(evalmati),add=TRUE, n=1) # Outline of the data
# Add cities locations and names
library(maps)
map.cities(country="Italy", label=T, minpop=50000)
Since your evalmati data is now a bathy object, you can adjust its appearance on the map like you would for the map background (adjust the number and width of contour lines, adjust the color gradient, etc). plot.bath() uses both image() and contour() so you should be able to get the same results as when you plot with image(). Please take a look at the help for plot.bathy() and the package vignettes for more examples.
I am not realy inside the subject, but Lovelace, R. "Introduction to visualising spatial data in R" might help you
https://github.com/Robinlovelace/Creating-maps-in-R/raw/master/intro-spatial-rl.pdf From section "Adding base maps to ggplot2 with ggmap" with small changes and data from https://github.com/Robinlovelace/Creating-maps-in-R/archive/master.zip
library(dplyr)
library(ggmap)
library(rgdal)
lnd_sport_wgs84 <- readOGR(dsn = "./Creating-maps-in-R-master/data",
layer = "london_sport") %>%
spTransform(CRS("+init=epsg:4326"))
lnd_wgs84_f <- lnd_sport_wgs84 %>%
fortify(region = "ons_label") %>%
left_join(lnd_sport_wgs84#data,
by = c("id" = "ons_label"))
ggmap(get_map(location = bbox(lnd_sport_wgs84) )) +
geom_polygon(data = lnd_wgs84_f,
aes(x = long, y = lat, group = group, fill = Partic_Per),
alpha = 0.5)

Z - Values for polygon (shapefile) in R

my goal is to create a 3D-Visualization in R. I have a shapefile of urban districts (Ortsteile) in Berlin and want to highlight the value (inhabitants/km²) as a z-value. I have implemented the shapefile into R and coloured the value for desnity ("Einwohnerd") as followed:
library(rgdal)
library(sp)
berlin=readOGR(dsn="C...etc.", layer="Ortsteile")
berlin#data
col <- rainbow(length(levels(berlin#data$Name)))
spplot(berlin, "Einwohnerd", col.regions=col, main="Ortsteil Berlins", sub="Datensatz der Stadt Berlin", lwd=.8, col="black")
How it is posible to refer a certain polygon (urban district) to a z-value (inhabitant/km²) and how can I highlight this z-value?
Hope that someone will have an answer!
Best regars
SB
Thanks for the answer, but I am still on my wy to find out the best to use the density as z-value so that I can create a 3D Model. I found out that it is not possible to use the polygons of the shape but that it is possible to rasterize the polygon and to use a matrix for a different perspective and rotation.
Here is the code but the final 3D visualization looks not sharp and good enough. Maybe it would be better to calculate the the z-value in anther way so that the first values did not start so high or to use the center of the polygon and than to draw a column in z-direction:
library(rgdal)
library(sp)
setwd("C:\\...")
berlin=readOGR(dsn="C:\\...\\Ortsteile", layer="Ortsteile")
col <- rainbow(length(levels(berlin#data$Name)))
spplot(berlin, "Einwohnerd", col.regions=col, main="Ortsteil Berlins",
sub="Datensatz der Stadt Berlin", lwd=.8, col="black")
library(raster)
raster <- raster(nrows=100, ncols=200, extent(berlin))
test <- rasterize(berlin, raster, field="Einwohnerd")
persp(test, theta = 40, phi = 40, col = "gold", border = NA, shade = 0.5)
for(i in seq(0,90,10)){
persp(test, theta = 40, phi = i, col = "gold", border = NA, shade = 0.5)
}
library(rgl)
library(colorRamps)
mat <- matrix(test[], nrow=test#nrows, byrow=TRUE)
image(mat)
persp3d(z = mat, clab = "m")
persp3d(z = mat, col = rainbow(10),border = "black")
persp3d(z = mat, facets = FALSE, curtain = TRUE)
Is this what you had in mind?
library(ggplot2)
library(rgdal) # for readOGR(...) and spTransform(...)
library(RColorBrewer) # for brewer.pal(...)
setwd("<directory with shapefile>")
map <- readOGR(dsn=".",layer="Ortsteile")
map <- spTransform(map,CRS=CRS("+init=epsg:4839"))
map.data <- data.frame(id=rownames(map#data), map#data)
map.df <- fortify(map)
map.df <- merge(map.df,map.data,by="id")
ggplot(map.df, aes(x=long, y=lat, group=group))+
geom_polygon(aes(fill=Einwohnerd))+
geom_path(colour="grey")+
scale_fill_gradientn(colours=rev(brewer.pal(10,"Spectral")))+
theme(axis.text=element_blank())+
labs(title="Berlin Ortsteile", x="", y="")+
coord_fixed()
Explanation
This is a great question, in that it provides an example of a very basic choropleth map using ggplot in R.
Shapefiles can be read into R using readOGR(...), producing SpatialDataFrame objects. The latter have basically two sections: a polygons section containing the coordinates of the polygon boundaries, and a data section containing information from the attributes table in the shapefile. These can be referenced, respectively, as map#polygons and map#data.
The code above reads the shapefile and transforms the coordinates to epsg:4839. Then we prepend the polygon ids (stored in the rownames) to the other information in map#data, creating map.data. Then we use the fortify(...) function in ggplot to convert the polygons to a dataframe suitable for plotting (map.df). This dataframe has a column id which corresponds to the id column in map.data. Then we merge the attribute information (map.data) into map.df based on the id column.
The ggplot calls create the map layers and render the map, as follows:
ggplot: set the default dataset to map.df; identify x- and y-axis columns
geom_polygon: identify column for fill (color of polygon)
geom_path: polygon boundaries
theme: turn off axis text
labs: title, turn off x- and y-axis labels
coord_fixed: ensures that the map is not distorted
A note on scale_fill_gradientn(...): this function assigns colors to the fill values by interpolating a color palette provided in the colours= parameter. Here we use the Spectral palette from www.colorbrewer.org. Unfotrunately, this palette has the colors revered (blue - red), so we use rev(...) to reverse the color order (high=red, low=blue). If you prefer the more highly saturated colors common in matlab, use library(colorRamps) and replace the call to scale_fill_gradientn(...) with:
scale_fill_gradientn(colours=matlab.like(10))+

Resources