Reputation: 1280
Summary: how do I use a SpatRaster object as a base map for ggmap?
Hi, I'm doing maps in R using ggplot. I want a base map from OpenStreetMaps, and then I want to plot polygons etc on top.
The ggmap package used to be perfect for this, but using Google maps is too complicated now, and OpenStreetMaps doesn't work at all.
I've come across ggspatial::annotation_map_tile()
, but it doesn't allow that many map types, and it's also super slow, so I'd like to avoid it if I can.
I've also come across maptiles::get_tiles()
, which has more options and seems way faster. 👍
The problem is that the SpatRaster object (from the terra package) it returns doesn't automatically work as a base map for ggmap. Is there a way to convert it?
I've managed to get part of the way there, by looking at what happens in ggmap's get_stamenmap()
, but the map comes out green. I assume it's because raster::raster()
and raster::as.raster()
don't work as I'd hope they might on this object type, but I don't know anything about these classes so I don't know where to go next.
library(dplyr)
library(ggmap)
library(sf)
library(maptiles)
nc <- st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
nc_osm <- get_tiles(nc, crop = TRUE)
# This is what it should look like
plot_tiles(nc_osm)
# I don't know these data types I'm trying to convert to
nc_ggmap <- nc_osm %>%
raster::raster() %>%
raster::as.raster()
# Set attributes manually, like in get_stamenmap()
class(nc_ggmap) <- c("ggmap", "raster")
attr(nc_ggmap, "bb") <- data.frame(ll.lat = 33.8,
ll.lon = -84.3,
ur.lat = 36.5,
ur.lon = -75.4)
attr(nc_ggmap, "source") <- ""
# Try to map it... green 💚
nc_ggmap %>%
ggmap()
By the way, I have managed to plot the object using ggplot, by calculating the colours of each pixel and using them for the fill
aesthetic, but I need to use that aesthetic for my polygons later on, which is why I'm quite keen to use the ggmap approach.
nc_osm %>%
terra::as.data.frame(xy = TRUE) %>%
as_tibble() %>%
mutate(hex = rgb(lyr.1, lyr.2, lyr.3, maxColorValue = 255)) %>%
ggplot(aes(x, y, fill = hex)) +
geom_tile() +
scale_fill_identity() +
coord_fixed() +
theme_void()
Upvotes: 3
Views: 1091
Reputation: 145
I don't really understand your question because it seems to me that you ask for something, and then afterwards you write that you managed to find a workaround to what you asked in the beginning.
That said, if what you need is simply having more than one fill aesthetic, you you can use the ggnewscale
package, here.
This way you can plot multiple layers with a different fill (or color, if needed) aesthetic for every layer.
Upvotes: 0