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.
Related
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
So, I have a dataset that has data for not only CONUS but also the island areas and Alaska. Now, I want to plot only the data for CONUS. I know I can subset it easily. But is there any easier way to that? Maybe an option in ggplot I don't know?
Here is the code:
ggplot() +
geom_polygon( data=usamap, aes(x=long, y=lat,group=group),colour="black", fill="white" )+
geom_point(data=df,aes(x=Longitude,y=Latitude))+
scale_colour_gradientn(name = "DL",colours = myPalette(10))+
xlab('Longitude')+
ylab('Latitude')+
coord_map(projection = "mercator")+
theme_bw()+
theme(legend.position = c(.93,.20),panel.grid.major = element_line(colour = "#808080"))+
ggsave("test.png",width=10, height=8,dpi=300)
Here is the dataset:
https://www.dropbox.com/s/k1z5uquhtc2b9nd/exported.csv?dl=0
You can do it and also use a decent projection at the same time:
library(ggplot2)
library(readr)
library(dplyr)
us <- map_data("state")
us <- fortify(us, region="region")
# for theme_map
devtools::source_gist("33baa3a79c5cfef0f6df")
# read your data and filter out points not in CONUS
read_csv("exported.csv") %>%
filter(Longitude>=-124.848974 & Longitude<=-66.885444,
Latitude>=24.396308 & Latitude<=49.384358) -> data
gg <- ggplot()
gg <- gg + geom_map(data=us, map=us,
aes(x=long, y=lat, map_id=region, group=group),
fill="#ffffff", color="#7f7f7f", size=0.25)
gg <- gg + geom_point(data=data,
aes(x=Longitude, y=Latitude),
color="#cb181d", size=1, alpha=1/10)
gg <- gg + coord_map("albers", lat0=39, lat1=45)
gg <- gg + theme_map()
gg
You have no aesthetic color mapping I can see, so your color scaling will have no impact. I used an alpha for overlapping/close points instead.
Looking at your reposted question, I think by far the best way is a simple subset. From this link, you can see the box around the continental USA is:
(-124.848974, 24.396308) - (-66.885444, 49.384358)
if you do a simple subset:
usamap<-usamap[usamap$Longitude > -124.848 &
usamap$Longitude < -66.886 &
usamap$Latitude > 24.3964 &
usamap$Latitude < 49.3844, ]
You will get your required points.
Since you said you'd be interested in a ggplot2 solution, you might consider modifying the arguments in coord_map(). For example:
coord_map(project = "globular",
xlim = c(-125, -66),
ylim = c(24, 50))
Of course, the "mercator" argument works, too!
I'm trying to plot a US map where each state is shaded by the count that it has. I've gotten the shading to work just fine. The problem I'm running into, however, is that the polygons look very jagged (I'm assuming something happened when I tried to merge the map_data('state') with my data frame of counts per state). My data frame before merging has 49 rows (Nevada was missing data in my set), and after merging has many more rows (expected for the long/lat items for the states) but the data appears to be copied correctly for each lat/long pair, so I'm unsure why the poly's are so jagged.
Code:
ggplot() +
geom_polygon(data=try1, aes(x=long, y=lat, group = group, fill= COUNT)) +
scale_fill_continuous(low='thistle2', high='darkred', guide='colorbar') +
theme_bw() + labs(fill="State Map Try Title1", title='Title2', x='', y='') +
scale_y_continuous(breaks=c()) +
scale_x_continuous(breaks=c()) +
theme(panel.border = element_blank())
Any help would be greatly appreciated (and obviously, if there is a better way to do it, I'm open to suggestions!).
You don't need to do the merge. You can use geom_map and keep the data separate from the shapes. Here's an example using the built-in USArrests data (reformatted with dplyr):
library(ggplot2)
library(dplyr)
us <- map_data("state")
arr <- USArrests %>%
add_rownames("region") %>%
mutate(region=tolower(region))
gg <- ggplot()
gg <- gg + geom_map(data=us, map=us,
aes(x=long, y=lat, map_id=region),
fill="#ffffff", color="#ffffff", size=0.15)
gg <- gg + geom_map(data=arr, map=us,
aes(fill=Murder, map_id=region),
color="#ffffff", size=0.15)
gg <- gg + scale_fill_continuous(low='thistle2', high='darkred',
guide='colorbar')
gg <- gg + labs(x=NULL, y=NULL)
gg <- gg + coord_map("albers", lat0 = 39, lat1 = 45)
gg <- gg + theme(panel.border = element_blank())
gg <- gg + theme(panel.background = element_blank())
gg <- gg + theme(axis.ticks = element_blank())
gg <- gg + theme(axis.text = element_blank())
gg
I encountered a similar problem when using ggplot2. As an alternative to #hrbrmstr 's solution, I found reloading the ggplot2 package (as well as rgdal/`maptools') resolved the issue for me.
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
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).