我想使用OSM数据绘制地图。使用osmdata
-R软件包可以轻松下载所需的数据。不幸的是,对于我所在的地区来说,并不是所有的数据都可以在OSM中获得。因此,我下载了一个具有我感兴趣的行政边界的区域的形状文件。我的问题是,我无法将形状文件信息与OSM信息一起绘制在一个图中。
我的工作流程:
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)
我可以用ggplot轻松地绘制形状文件或osmdata。但我不能把两者都放在一个情节里。我推理的错误是什么?
我的绘图代码:
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)")
要测试它,只需注释掉geom_path()
或geom_sf()
行即可。
我想,这与坐标有关,但我不知道如何分配正确的坐标。
谢谢你的帮助!
这确实与坐标系有关。我建议您也使用sf
将ot.shp
读取为R,然后更改坐标系。这将用取代您代码的第一部分(在下载OSM数据之前(
lpz_ot = st_read('ot.shp') %>% st_transform(crs = 4326)
要绘制它,只需将ggplot代码上的geom_path
行替换为:
geom_sf(data = lpz_ot)