To integrate ggplot2 with autoplot.OpenStreetMap, follow these steps:
install.packages("ggplot2")
install.packages("openstreetmap")
library(ggplot2)
library(openstreetmap)
get_bbox()
function from the openstreetmap
package:bbox <- get_bbox(c(lon_min, lat_min), c(lon_max, lat_max), format_out = "bbox")
Replace lon_min
, lat_min
, lon_max
, and lat_max
with the longitude and latitude coordinates for the bottom left and top right corners of your desired map area.
get_map()
from the ggmap
package to download a map image:map <- get_map(bbox, source = "osm")
autoplot()
from the ggplot2
package and geom_tile()
to plot the map:ggmap(map) +
geom_tile(data = mapdata,
aes(x = lon, y = lat, fill = value), alpha = .8) +
scale_fill_gradient(low = "white", high = "blue") +
theme(legend.position = "bottom", plot.title = element_text(hjust = 0.5)) +
ggtitle("My OpenStreetMap plot")
Assuming you have created a mapdata
dataframe with suitable values for lon
, lat
, and value
, this code will plot an OpenStreetMap image of your desired area with tiles overlaid to represent your data. If mapdata
has no spatial attributes spatial coordinates can be added using a projection like st_transform()
from the sf
package.
Asked: 2023-06-07 22:09:54 +0000
Seen: 11 times
Last updated: Jun 07 '23