Reputation: 247
I want to plot a map using OSM Data. The needed data can be downloaded easily with the osmdata
-R-package. Unfortunately for my region not all data is available in OSM. Therefor I downloaded a shapefile of the Region with the administrative boundaries I am interessed in. My problem is, that I cant plot the shapefile information together with the OSM information in one plot.
My Workflow:
library(raster)
library(rgdal)
library(tidyverse)
library(broom)
library(rgeos)
library(osmdata)
library(sf)
# Download shapefile from Leipzig with "Ortteile" (engl. urban districts)
https://gruenlink.de/1py4
# import Ortsteile Leipzigs
lpz_ot <- readOGR("ot.shp")
names(lpz_ot)
# convert spatial object to a ggplot ready data frame
lpz_ot_df <- tidy(lpz_ot,OT = "id")
# make sure the shapefile attribute table has an id column
lpz_ot$id <- rownames(lpz_ot@data)
# join the attribute table from the spatial object to the new data frame
lpz_ot_df <- lpz_ot_df %>%
left_join(lpz_ot@data,by = "id")
# check names
names(lpz_ot_df)
# Download interessting OSM Data (e.g. railways and tramlines)
#bounding box Leipzig
lpz_box <- opq(bbox = 'Leipzig')
# Plygon for Leipzig
lpz_poly <- getbb(place_name = c("Leipzig"),format_out = "polygon")
# railways and tramlines in Leipzig (in bounding box)
sv <- lpz_box%>%
add_osm_feature(key = "railway", value = c("tram","rail")) %>%
osmdata_sf()
# railways and tramlines in Leipzig (within administrative boundaries of Leipzig)
svt <- trim_osmdata (sv,lpz_poly,exclude =TRUE)
I can easily plot the shape-file or the osmdata with ggplot. But I can't plot both in one plot. What is my error in reasining?
My plot code:
ggplot() +
geom_path(data = lpz_ot_df, aes(x = long, y = lat, group = group,color="black"))+
geom_sf(data = svt$osm_lines, aes(color = railway),size=1.3) +
theme_void() +
guides(color = FALSE)+
labs(title ="Urban districts in Leipzigs (with railwaynet)")
To test it, just comment out geom_path()
or the geom_sf()
lines.
I think, it has something to do with the coordiates, but I dont know how to assign the correct coordiates.
Thank you for any help!
Upvotes: 0
Views: 642
Reputation: 315
This has indeed to do with the coordinate systems. I recommend you to use sf
also to read the ot.shp
into R, and then change the coordinate system. That will replace the first part of your code (before downloading OSM data) with:
lpz_ot = st_read('ot.shp') %>% st_transform(crs = 4326)
To plot it, just replace the geom_path
line on your ggplot code with:
geom_sf(data = lpz_ot)
Upvotes: 1