How to colour a single country in R maps package (worldhires) - r

I am new here and I am trying to plot points on a map of a coastal region - therefore I would like to show a coastline and colour just one country, surrounded by adjoining countries.
My code is
library(maps)
library(mapdata)
map("worldHires", xlim=c(-90,-70), ylim=c(-20,-2), # Re-defines the latitude and longitude range
col = "gray", fill=TRUE)
However I would like to colour in just Peru. I have so far managed to do this:
map('worldHires', 'Peru', col = "grey90", fill=TRUE, xlim=c(-90,-70), ylim=c(-20,-2))
but this doesn't show adjoining countries, and I would really like to show all adjoining countries and just colour Peru.
I have seen advice in another thread using the simple map tool - but there is slightly less detail (see below)
library(maptools)
data(wrld_simpl)
plot(wrld_simpl,
col = c(gray(.80), "red")[grepl("Peru", wrld_simpl#data$NAME) + 1],
xlim=c(-90,-70), ylim=c(-20,-2))
Does anyone know how to do it using worldhires? It's probably really simple and I just haven't worked it out.

The trick is to use map() to extract the Peru boundaries, then overplotting the Peru fill on a worlmap outline.
library(maps)
library(mapdata)
peru <- map("worldHires", regions="Peru", plot=FALSE, fill=TRUE)
map("worldHires", xlim=c(-100,-30), ylim=c(-30,10))
map(peru, col="red", fill=TRUE, add=TRUE)

A Hadleyverse version via ggplot:
library(maps)
library(mapdata)
library(ggplot2)
coast_map <- fortify(map("worldHires", fill=TRUE, plot=FALSE))
gg <- ggplot()
gg <- gg + geom_map(data=coast_map, map=coast_map,
aes(x=long, y=lat, map_id=region),
fill="white", color="black")
gg <- gg + geom_map(data=data.frame(region="Peru"), map=coast_map,
aes(map_id=region), fill="steelblue")
gg <- gg + xlim(-90,-70) + ylim(-20,-2)
gg <- gg + coord_map()
gg <- gg + theme_bw()
gg

Related

Can I change background map in ggplot2?

I just had a play with ggplot2 in R, with syntax like
geom_map(data=world, map=world
aes(x=long, y=lat, map_id=region),
color="white", fill="#7f7f7f", size=0.05, alpha=1/4)
That gives me the world map, is it possible to only get UK map as background map?
Many thanks
Peddie
You can also do something like:
library(ggplot2)
library(ggthemes)
library(raster)
library(rgeos)
gbr <- getData("GADM", country="GBR", level=0)
gbr <- gSimplify(gbr, 0.01)
gbr_map <- fortify(gbr)
gg <- ggplot()
gg <- gg + geom_map(map=gbr_map, data=gbr_map,
aes(x=long, y=lat, map_id=id),
fill="#7f7f7f")
gg <- gg + coord_map()
gg <- gg + theme_map()
gg
Once my ggalt package is in CRAN you can even use a decent projection.
Also check out ggplot2::borders()
library(ggplot2)
ggplot() +
borders(reg="UK", color="white", fill="#7f7f7f", alpha=1/4)
The result should be equal to the one from #eipi10.
library(maps)
library(ggplot2)
dat=map_data("world")
ggplot() +
geom_map(data=dat[dat$region=="UK",], map=dat[dat$region=="UK",],
aes(x=long, y=lat, map_id=region),
color="white", fill="#7f7f7f", size=0.05, alpha=1/4) +
coord_fixed()
The library ggmap works very well with ggplot2.
You could try this:
library(ggmap)
#Google API
register_google(key = "your_api_key")
map <- get_map(location = 'UK', zoom = 6)
ggmap(map)
and add geom as you like.

What is the "Simplest" way to add a scale to a map in ggmap

For real, I searched everywhere, and coding a scale in a map is so hard...
Adding scale bar to ggplot map
Is there a way to add a scale bar (for linear distances) to ggmap?
Could it be possible to make a simple line that scale differently to the zoom preset that we select in the function?
I have this simple map:
library(ggmap)
pngMAP_df2 = get_map(location = c(-90.5, -0.5), source = "google", zoom = 8,color = "bw")
s = ggmap(pngMAP_df2)
s
I wanted to add as well GPS coordinate in this graph:
myGPS = data.frame(lat=c( -0.6850556,-0.6854722, -0.6857778 ),lon=c(-90.22275,-90.22261, -90.22272))
Is it easy to implement?
I just want to add something realllllllllly simple. Like a line with always a round number that give an indication of the zoom in the map.
Also, is it possible with this code to make the map look even simpler. Like seeing the water in white and the contour of the land in black?
Thanks,
Something like:
library(rgdal)
library(rgeos)
library(ggplot2)
library(ggthemes)
library(ggsn)
URL <- "https://osm2.cartodb.com/api/v2/sql?filename=public.galapagos_islands&q=select+*+from+public.galapagos_islands&format=geojson&bounds=&api_key="
fil <- "gal.json"
if (!file.exists(fil)) download.file(URL, fil)
gal <- readOGR(fil, "OGRGeoJSON")
# sample some points BEFORE we convert gal
rand_pts <- SpatialPointsDataFrame(spsample(gal, 100, type="random"), data=data.frame(id=1:100))
gal <- gSimplify(gUnaryUnion(spTransform(gal, CRS("+init=epsg:31983")), id=NULL), tol=0.001)
gal_map <- fortify(gal)
# now convert our points to the new CRS
rand_pts <- spTransform(rand_pts, CRS("+init=epsg:31983"))
# and make it something ggplot can use
rand_pts_df <- as.data.frame(rand_pts)
gg <- ggplot()
gg <- gg + geom_map(map=gal_map, data=gal_map,
aes(x=long, y=lat, map_id=id),
color="black", fill="#7f7f7f", size=0.25)
gg <- gg + geom_point(data=rand_pts_df, aes(x=x, y=y), color="steelblue")
gg <- gg + coord_equal()
gg <- gg + scalebar(gal_map, dist=100, location="topright", st.size=2)
gg <- gg + theme_map()
gg
This would be the complete answer with specific points on the map.
library(rgdal)
library(rgeos)
library(ggplot2)
library(ggthemes)
library(ggsn)
myGPS = data.frame(lat=c( -0.6850556,-0.6854722, -0.6857778 ),lon=c(-90.22275,-90.22261, -90.22272))
coord.deg = myGPS
class(coord.deg)
## "data.frame"
coordinates(coord.deg)<-~lon+lat
class(coord.deg)
## "SpatialPointsDataFrame"
## attr(,"package")
## "sp"
# does it have a projection/coordinate system assigned?
proj4string(coord.deg) # nope
## NA
# Manually tell R what the coordinate system is
proj4string(coord.deg)<-CRS("+proj=longlat +ellps=WGS84 +datum=WGS84")
# now we can use the spTransform function to project. We will project
# the mapdata and for coordinate reference system (CRS) we will
# assign the projection from counties
coord.deg<-spTransform(coord.deg, CRS(proj4string(gal)))
# double check that they match
identical(proj4string(coord.deg),proj4string(gal))
## [1] TRUE
my_pts <- SpatialPointsDataFrame(coords = coord.deg, data=data.frame(id=1:length(coord.deg)))
URL <- "https://osm2.cartodb.com/api/v2/sql?filename=public.galapagos_islands&q=select+*+from+public.galapagos_islands&format=geojson&bounds=&api_key="
fil <- "gal.json"
if (!file.exists(fil)) download.file(URL, fil)
gal <- readOGR(fil, "OGRGeoJSON")
gal <- gSimplify(gUnaryUnion(spTransform(gal, CRS("+init=epsg:31983")), id=NULL), tol=0.001)
gal_map <- fortify(gal)
rand_pts <- spTransform(my_pts, CRS("+init=epsg:31983"))
# ggplot can't deal with a SpatialPointsDataFrame so we can convert back to a data.frame
my_pts <- data.frame(my_pts)
my_pts.final = my_pts[,2:3]
# we're not dealing with lat/long but with x/y
# this is not necessary but for clarity change variable names
names(my_pts.final)[names(my_pts.final)=="lat"]<-"y"
names(my_pts.final)[names(my_pts.final)=="lon"]<-"x"
gg <- ggplot()
gg <- gg + geom_map(map=gal_map, data=gal_map,
aes(x=long, y=lat, map_id=id),
color="black", fill="#FFFFFF", size=.5)
gg <- gg + coord_equal()
gg <- gg + ggsn:::scalebar(gal_map, dist=50, location="bottomleft", st.size=5)
gg <- gg + theme_map()
gg <- gg + geom_point(data=my_pts.final, aes(x=x, y=y), color="red")
gg

How to map New York City using map function in R

I want to draw a map of NYC using the function map() in R.
I tried doing something like this:
map('state', region = c('new york', 'new jersey'),
xlim=c(-74.12,-73.85), ylim=c(40.58,40.87))
Using the coordinates to zoom in, but the map looks small and not very readable.
Is there a better way to do this?
Thanks,
Elena
You can also stay in base graphics/ggplot and use better shapefiles. There are many NYC shapefiles (those are just a few). I grabbed the borough borders:
library(sp)
library(rgdal)
library(rgeos)
library(ggplot2)
library(ggthemes)
url <- "http://www.nyc.gov/html/dcp/download/bytes/nybb_15b.zip"
fil <- basename(url)
if (!file.exists(fil)) download.file(url, fil)
fils <- unzip(fil)
nyc <- readOGR(fils[1], ogrListLayers(fils[1])[1], stringsAsFactors=FALSE)
# base
plot(nyc, lwd=0.5, asp=1)
# ggplot2
# simplifying the polygons speeds up ggplot2 a bit
nyc_map <- fortify(gSimplify(nyc, 0.05))
gg <- ggplot()
gg <- gg + geom_map(data=nyc_map, map=nyc_map,
aes(x=long, y=lat, map_id=id),
color="black", fill="white", size=0.25)
gg <- gg + coord_equal()
gg <- gg + theme_map()
gg
That particular shapefile is pre-projected, so you just need to ensure a 1:1 aspect ratio for the plots.
Other shapefiles give varying levels of detail.
I may be wrong, but I don't think the maps package has high resolution map data for this kind of thing.
You could try the ggmap package instead:
library(ggmap)
mymap <- get_map(location = "New York", maptype = "roadmap")
ggmap(mymap)
See the ggmap paper for a brief intro to the package.

Add bathymetry lines to ggplot using marmap package and getNOAA.bathy

I am wanting to add bathymetry lines to a map plot I am looking at. I am plotting points off the coast and we are interested as to how close to the continental shelf they are. I have seen a package called Marmap - but now I am using ggplot as it gives a higher resolution.
The code I've seen for getting bathymetry lines is this:
library(marmap)
Peru.bath <- getNOAA.bathy (lon1 = -90, lon2 = -70, lat1 = -20,
lat2 = -2, resolution = 10)
plot(Peru.bath)
The code I'm using which I want to add the bathymetry lines to is below:
coast_map <- fortify(map("worldHires", fill=TRUE, plot=FALSE))
gg <- ggplot()
gg <- gg + geom_map(data=coast_map, map=coast_map,
aes(x=long, y=lat, map_id=region),
fill="white", color="black") +
theme(panel.background = element_blank()) +
theme(panel.grid.major = element_blank()) +
theme(panel.grid.minor = element_blank()) +
theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank())
gg <- gg + xlab("") + ylab("")
gg <- gg + geom_map(data=data.frame(region="Peru"), map=coast_map,
aes(map_id=region), fill="gray")
gg <- gg + xlim(-90,-70) + ylim(-20,-2)
gg <- gg + coord_map()
gg
Therefore I assumed it would be
gg <- gg + Peru.bath
However I am getting 'Error: Don't know how to add Peru.bath to a plot'
NB Just to make it clear, I do not have bathymetry data, I just wish to plot known shelf lines onto a map I have created, if that is possible.
I've just updated the development version of marmap on github. You can install it with:
library(devtools)
install_github("ericpante/marmap")
A function autoplot.bathy() for plotting bathy objects with ggplot2 is now included. Be sure to check it's help file and the examples to see what's possible. Here is an example with your dataset dat:
library(marmap) ; library(ggplot2)
dat <- getNOAA.bathy(-90,-70,-20,-2,res=4, keep=TRUE)
# Plot bathy object using custom ggplot2 functions
autoplot(dat, geom=c("r", "c"), colour="white", size=0.1) + scale_fill_etopo()
If you want to (i) add isobath lines to your map and (ii) determine the depth of your data points using get.depth() it would be much easier to stick with standard plots (marmap is designed to work with these). As a matter of fact, the "better resolution" you mention has nothing to do with base graphics nor ggplot2. In your example, the coastline you're plotting comes from the "worldHires" dataset from package mapdata and it has nothing to do with ggplot2. Indeed, you can add the same coastline on marmap plots.
Here is some code to produce two more than decent maps using base graphics and marmap:
library(marmap) ; library(mapdata)
# Get bathymetric data
dat <- getNOAA.bathy(-90,-70,-20,-2,res=4, keep=TRUE)
# Create nice color palettes
blues <- c("lightsteelblue4", "lightsteelblue3", "lightsteelblue2", "lightsteelblue1")
greys <- c(grey(0.6), grey(0.93), grey(0.99))
## First option for plotting
plot(dat, land=TRUE, n=100, lwd=0.03)
map("worldHires", res=0, add=TRUE)
# Second option
plot(dat, im=TRUE, land=TRUE, bpal=list(c(min(dat),0,blues),c(0,max(dat),greys)), lwd=.05, las=1 )
map("worldHires", res=0, lwd=0.7, add=TRUE)
# Add -200m and -1000m isobath
plot(dat, deep=-200, shallow=-200, step=0, lwd=0.5, drawlabel=TRUE, add=TRUE)
plot(dat, deep=-1000, shallow=-1000, step=0, lwd=0.3, drawlabel=TRUE, add=TRUE)
Note that the resolution used here is not the highest possible. the res argument of getNOAA.bathy() is set to 4 here. This downloads a 2.7Mb dataset that can be saved locally by setting the keep argument to TRUE. The highest resolution possible would be res=1, but in my opinion, it is overkill for such a wide geographical scale. This code produces the 2 plots below:
Running a bit short on time this morning, but this should help you get started (and, can no doubt be improved by other R geo folks:
library(maps)
library(mapdata)
library(ggplot2)
library(marmap)
library(Grid2Polygons)
coast_map <- fortify(map("worldHires", fill = TRUE, plot = FALSE))
Peru.bath <- getNOAA.bathy (lon1 = -90, lon2 = -70, lat1 = -20,
lat2 = -2, resolution = 10)
peru_bathy_df <- Grid2Polygons(as.SpatialGridDataFrame(Peru.bath),
level=TRUE, pretty=TRUE)
peru_bathy_map <- fortify(peru_bathy_df)
gg <- ggplot()
gg <- gg + geom_map(data=peru_bathy_map, map=peru_bathy_map,
aes(map_id=id), color="black", fill="white")
gg <- gg + geom_map(data=coast_map, map=coast_map,
aes(x=long, y=lat, map_id=region),
fill="white", color="black")
gg <- gg + geom_map(data=data.frame(region="Peru"), map=coast_map,
aes(map_id=region), fill="steelblue")
gg <- gg + xlim(-90,-70) + ylim(-20,-2)
gg <- gg + coord_map()
gg <- gg + theme_bw()
gg
Obviously you want a better picture than that, but the basic idea is to get it converted into an object that ggplot can handle (so, a SpatialPolygonsDataFrame). Lots of good non-ggplot examples in the bathy and Grid2Polygons help.
NOTE: these take some time to convert/render and the bathy examples do show a way to do this without ggplot that will be much faster.

Overlaying polygons on ggplot map

I'm struggling to overlay neighborhood boundaries on a google map. I'm trying to follow this code. My version is below. Do you see anything obviously wrong?
#I set the working directory just before this...
chicago = readOGR(dsn=".", layer="CommAreas")
overlay <- spTransform(chicago,CRS("+proj=longlat +datum=WGS84"))
overlay <- fortify(overlay)
location <- unlist(geocode('4135 S Morgan St, Chicago, IL 60609'))+c(0,.02)
ggmap(get_map(location=location,zoom = 10, maptype = "terrain", source = "google",col="bw")) +
geom_polygon(aes(x=long, y=lat, group=group), data=overlay, alpha=0)+
geom_path(color="red")
Any insight would be much appreciated. Thanks for your help and patience.
This worked for me:
library(rgdal)
library(ggmap)
# download shapefile from:
# https://data.cityofchicago.org/api/geospatial/cauq-8yn6?method=export&format=Shapefile
# setwd accordingly
overlay <- readOGR(".", "CommAreas")
overlay <- spTransform(overlay, CRS("+proj=longlat +datum=WGS84"))
overlay <- fortify(overlay, region="COMMUNITY") # it works w/o this, but I figure you eventually want community names
location <- unlist(geocode('4135 S Morgan St, Chicago, IL 60609'))+c(0,.02)
gmap <- get_map(location=location, zoom = 10, maptype = "terrain", source = "google", col="bw")
gg <- ggmap(gmap)
gg <- gg + geom_polygon(data=overlay, aes(x=long, y=lat, group=group), color="red", alpha=0)
gg <- gg + coord_map()
gg <- gg + theme_bw()
gg
You might want to restart your R session in the event there's anything in the environment causing issues, but you can set the line color and alpha 0 fill in the geom_polygon call (like I did).
You can also do:
gg <- gg + geom_map(map=overlay, data=overlay,
aes(map_id=id, x=long, y=lat, group=group), color="red", alpha=0)
instead of the geom_polygon which gives you the ability to draw a map and perform aesthetic mappings in one call vs two (if you're coloring based on other values).

Resources