Create bubble plot in R using satellite map - r

I already created a bubble plot using the following code:
library(ggplot2)
library(sp)
library(raster)
library(maps)
library(mapdata)
library(maptools)
library(gstat)
library(ggmap)
xy <- se_pp[,c("longitude_s", "latitude_s")]
nl <- getData('GADM', country="Netherlands", level=2) #raster data, format SpatialPolygonsDataFrame
# coercing the polygon outlines to a SpatialLines object
spl <- list("sp.lines", as(nl, "SpatialLines"))
SPDF <- SpatialPointsDataFrame(coords=xy, data=se_pp)
projection(SPDF)<- "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0"
coordinates(SPDF)[1:5,] #retrieves spatial coordinates form the dataframe
bubble(SPDF, "Quantity", sp.layout=spl, main="Plaice Quantity (#/km2), end summer (Sand Engine)")
Now I get a map of the Dutch coast containing the bubble plot (via getData).
Unfortunately this is a very simple map.
I would like to have a satellite map of the same area, which shows more detail, to show my bubble plot.
Does anyone know if this is possible?
Thanks.

I am not sure if you still check SO. But, I leave one approach for you. You can play with the values in zoom to identify the best zoom for your purpose. The CRAN manual of ggmap offers you more examples. Please have a look.
map <- get_map(location = 'netherlands', zoom = 7,
source = 'google',
maptype = 'satellite')
ggmap(map)

Related

Issues plotting spatial point data using tmap

I have created a class Large SpatialPointDataFrame from a csv file, and I am trying to plot the data points using tmap. When I plotted the SpatialPointDataFrame using plot(), everything looked fine. However, when I tried to plot it using tmap, it only shows one single point plus it is not where it should be, btw, the point that got shown is the last item in the data frame.
I'm thinking there might be something wrong with my projecton? CRS(Using SVY21 or EPSG:3414) properties of the SpatialPointDataFrame:
crs: +init=epsg:3414 +proj=tmerc +lat_0=1.366666666666667 +lon_0=103.8333333333333 +k=1 +x_0=28001.642 +y_0=38744.572 +ellps=WGS84 +units=m +no_defs
This is how I converted the dataframe to a spatialpointdataframe, where listing is the original dataframe read from a csv file.
coords <- listing[ , c("latitude", "longitude")]
crs <- CRS("+init=epsg:3414")
listing_sp <- SpatialPointsDataFrame(coords = coords, listing, proj4string = crs)
Any suggestions on how I should debug?
In your code, where you have crs <- CRS("+init=epsg:3414"), you are assigning a projection but your source data has not yet been transformed to that projection. If your source data is in lat/lon it's meant to be used with the WGS84 projection (epsg code 4326).
Once you create your spatialPointDataFrame using the projection matching your coordinates, you simply have to reproject using spTransform. To reproject to SVY21, you still need to transform. Can't test without some reproducible data but it should look like this.
coords <- listing[ , c("latitude", "longitude")]
crs <- CRS("+init=epsg:4326")
listing_sp <- SpatialPointsDataFrame(coords = coords, listing, proj4string = crs)
listing_sp_svy21 <- spTransform(listing_sp, CRS("+init=epsg:3414"))

Spatial polygons with messed up shape

I am new to spatial data. My goal is to get the gpx files from openstreetmap and plot polygons of Hungary's boundaries. I could successfully plot the boundaries under Járások but there are some boundaries under Kistérségek which are messed up, containing loops between points.
Image
Reproducable example for a specific boundary
library(XML)
library(magrittr)
library(sp)
parsed <- xmlParse("http://osmrm.openstreetmap.de/gpx.jsp?relation=1368104") %>% xmlToList()
coord <- do.call(rbind, parsed$rte)
name <- coord[1, 1]
coord <- coord[-(1:2), ]
coord <- apply(coord, 2, as.numeric)
poly <- Polygons(list(Polygon(coord)), name)
sp <- SpatialPolygons(list(poly), proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
plot(sp)
Result
Is the error because I missed something, or is it simply an issue with openstreetmap data? Any help is appreciated.

Plotting a shapefile on a raster layer in R

I want to plot a raster layer with points from a shapefile on top.
I have checked previous answers on this, but i still have a problem.
I can plot the point shapefile and the raster layer separately without problem, but not together.
As far as I can see they should be in same projection and location.
require(maptools)
myproj <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
shape <- readShapeSpatial("directory/mypoints.shp", proj4string = CRS(myproj))
plot(r <- raster(listVI[200]))
plot(shape)
I found the answer, I will put it here for others who may encounter same problem.
The solution is simply: (as long as raster and shapefile is in same CRS)
plot(r)
plot(shape, add = TRUE)

Map raw data and mean data based on the shapefile

sI have the dataset (pts) like this:
x <- seq(-124.25,length=115,by=0.5)
y <- seq(26.25,length=46,by=0.5)
z = 1:5290
longlat <- expand.grid(x = x, y = y) # Create an X,Y grid
pts=data.frame(longlat,z)
names(pts) <- c( "x","y","data")
I knew that I can map the dataframe (pts) into a map by doing:
library(sp)
library(rgdal)
library(raster)
library(maps)
coordinates(pts)=~x+y
proj4string(pts)=CRS("+init=epsg:4326") # set it to long, lat
pts = spTransform(pts,CRS(" +init=epsg:4326 +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0"))
pts <- as(pts, "SpatialPixelsDataFrame")
r = raster(pts)
projection(r) = CRS(" +init=epsg:4326 +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0")
plot(r)
map("usa",add=T)
Now I would like to create a separate map which shows the means of pts across different regions. The shapefile I want to use is from ftp://ftp.epa.gov/wed/ecoregions/cec_na/NA_CEC_Eco_Level2.zip , however, this is a north america map. How can I create the map showing only US based on this north america map? Or is there another better way to do this? thanks so much.
I think that cutting out the non-US data based on the data in the shapefile alone would be hard, since the regions do not correspond to political boundaries - that could be done with rgeos though.
Assuming that "eco" is a SpatialPolygonsDataFrame read in by rgdal::readOGR or maptools::readShapeSpatial, see the available key data for indexing:
sapply(as.data.frame(eco), function(x) if(!is.numeric(x)) unique(x) else NULL)
If you just want to plot it, set up a map with only the US region to start with and then overplot.
library(maps)
map("usa", col = "transparent")
We see that the data is in Lambert Azimuthal Equal Area:
proj4string(eco)
[1] " +proj=laea +lat_0=45 +lon_0=-100 +x_0=0 +y_0=0 +a=6370997 +b=6370997 +units=m +no_defs"
So
require(rgdal)
eco.laea <- spTransform(eco, CRS("+proj=longlat +ellpse=WGS84"))
plot(eco.laea, add = TRUE)
If you want to plot in the original Lambert Azimuthal Equal Area you'll need to get the bounding box in that projection and start the plot based on that, I just used existing data to make an easy example. I'm pretty sure the data could also be cropped with rgeos against another boundary too, but depends what you actually want.

R: creating a map of selected Canadian provinces and U.S. states

I am attempting to create a map of selected Canadian provinces/territories and selected U.S. states. So far the nicest maps appear to be those generated with GADM data: http://www.gadm.org/
However, I have not been able to plot the U.S. and Canada on the same map or plot only selected provinces/territories and states. For example, I am interested in Alaska, Yukon, NWT, British Columbia, Alberta, and Montana among others.
Also, the U.S. map appears to be split along the international dateline.
Can someone please help me to:
plot the aforementioned provinces/territories and states on a single map
avoid having the U.S. split along the International dateline
overlay a latitude-longitude grid
select a specific projection, maybe the polyconic.
Maybe spplot does not allow users to specify projections. I did not see an option to select a projection on the spplot help page. I know how to select projections with the map function in the maps package but those maps did not appear to look as nice and I could not plot the desired subset of provinces/territories and states with that function either.
I do not know how to begin adding a latitude-longitude grid. However, Section 3.2 of the file 'sp.pdf' seems to address the topic.
Below is the code I have come up with so far. I have loaded every map-related package I have stumbled upon and commented out GADM data except for provincial/territorial or state boundaries.
Unfortunately, so far I have only managed to plot maps of Canada or the U.S.
library(maps)
library(mapproj)
library(mapdata)
library(rgeos)
library(maptools)
library(sp)
library(raster)
library(rgdal)
# can0<-getData('GADM', country="CAN", level=0) # Canada
can1<-getData('GADM', country="CAN", level=1) # provinces
# can2<-getData('GADM', country="CAN", level=2) # counties
plot(can1)
spplot(can1, "NAME_1") # colors the provinces and provides
# a color-coded legend for them
can1$NAME_1 # returns names of provinces/territories
# us0 <- getData('GADM', country="USA", level=0)
us1 <- getData('GADM', country="USA", level=1)
# us2 <- getData('GADM', country="USA", level=2)
plot(us1) # state boundaries split at
# the dateline
us1$NAME_1 # returns names of the states + DC
spplot(us1, "ID_1")
spplot(us1, "NAME_1") # color codes states and
# provides their names
#
# Here attempting unsuccessfully to combine U.S. and Canada on one map.
# Attempts at selecting given states or provinces have been unsuccessful.
#
plot(us1,can1)
us.can1 <- rbind(us1,can1)
Thanks for any help. So far I have made no progress with Steps 2 - 4 above. Perhaps I am asking for too much. Perhaps I should simply switch to ArcGIS and try that software.
I have read this StackOverflow post:
Can R be used for GIS?
EDIT
I have now borrowed an electronic copy of 'Applied Spatial Data Analysis with R' Bevand et al. (2008) and downloaded (or located) associated R code and data from the book's website:
http://www.asdar-book.org/
I also found some nice-looking GIS-related R code here:
https://sites.google.com/site/rodriguezsanchezf/news/usingrasagis
If and when I learn how to accomplish the desired objectives I will post solutions here. Although I may eventually move to ArcGIS if I cannot accomplish the objectives in R.
To plot multiple SpatialPolygons objects on the same device, one approach is to specify the geographic extent you wish to plot first, and then using plot(..., add=TRUE). This will add to the map only those points that are of interest.
Plotting using a projection, (e.g. a polyconic projection) requires first using the spTransform() function in the rgdal package to make sure all the layers are in the same projection.
## Specify a geographic extent for the map
## by defining the top-left and bottom-right geographic coordinates
mapExtent <- rbind(c(-156, 80), c(-68, 19))
## Specify the required projection using a proj4 string
## Use http://www.spatialreference.org/ to find the required string
## Polyconic for North America
newProj <- CRS("+proj=poly +lat_0=0 +lon_0=-100 +x_0=0
+y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs")
## Project the map extent (first need to specify that it is longlat)
mapExtentPr <- spTransform(SpatialPoints(mapExtent,
proj4string=CRS("+proj=longlat")),
newProj)
## Project other layers
can1Pr <- spTransform(can1, newProj)
us1Pr <- spTransform(us1, newProj)
## Plot each projected layer, beginning with the projected extent
plot(mapExtentPr, pch=NA)
plot(can1Pr, border="white", col="lightgrey", add=TRUE)
plot(us1Pr, border="white", col="lightgrey", add=TRUE)
Adding other features to the map, such as highlighting jurisdictions of interest, can easily be done using the same approach:
## Highlight provinces and states of interest
theseJurisdictions <- c("British Columbia",
"Yukon",
"Northwest Territories",
"Alberta",
"Montana",
"Alaska")
plot(can1Pr[can1Pr$NAME_1 %in% theseJurisdictions, ], border="white",
col="pink", add=TRUE)
plot(us1Pr[us1Pr$NAME_1 %in% theseJurisdictions, ], border="white",
col="pink", add=TRUE)
Here is the result:
Add grid-lines when a projection is used is sufficiently complex that it requires another post, I think. Looks as if #Mark Miller as added it below!
Below I have modified PaulG's outstanding answer to display a latitude-longitude grid. The grid is coarser than I would like, but might be adequate. I use the United Kingdom with the code below. I do not know how to include the result in this post.
library(rgdal)
library(raster)
# define extent of map area
mapExtent <- rbind(c(0, 62), c(5, 45))
# BNG is British National Grid
newProj <- CRS("+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.999601271625
+x_0=400000 +y_0=-100000 +ellps=airy +units=m +no_defs")
mapExtentPr <- spTransform(SpatialPoints(mapExtent,
proj4string=CRS("+proj=longlat")),
newProj)
# provide a valid 3 letter ISO country code
# obtain a list with: getData("ISO3")
uk0 <- getData('GADM', country="GBR", level=0) # UK
uk1 <- getData('GADM', country="GBR", level=1) # UK countries
uk2 <- getData('GADM', country="GBR", level=2) # UK counties
# United Kingdom projection
uk1Pr <- spTransform(uk1, newProj)
# latitude-longitude grid projection
grd.LL <- gridlines(uk1, ndiscr=100)
lat.longPR <- spTransform(grd.LL, newProj)
# latitude-longitude text projection
grdtxt_LL <- gridat(uk1)
grdtxtPR <- spTransform(grdtxt_LL, newProj)
# plot the map, lat-long grid and grid labels
plot(mapExtentPr, pch=NA)
plot(uk1Pr, border="white", col="lightgrey", add=TRUE)
plot(lat.longPR, col="black", add=TRUE)
text(coordinates(grdtxtPR),
labels=parse(text=as.character(grdtxtPR$labels)))
Result looks like:

Resources