r - 使用 ggplot2/geom_sf 绘图时修复 osm 道路中的间隙

标签 r ggplot2 openstreetmap sf overpass-api

当使用 osmdata 绘制从 osm 下载的道路数据时,如果在 geom_sf 中使用较大的 size 值,生成的绘图中会有间隙(见图片)。

这是一个使用伦敦西南部一段道路的可重现示例。绘图时如何去除线条中的白色间隙?

library(tidyverse)
library(sf)
library(osmdata)

# define bounding box for osm data
my_bbox <- 
  matrix(c(-0.2605616, -0.2605616,
           -0.2004485, -0.2004485,
           -0.2605616, 51.4689943,
           51.4288980, 51.4288980,
           51.4689943, 51.4689943),
         ncol = 2)
bbox_sf <- st_geometry(st_polygon(x = list(my_bbox)))
st_crs(bbox_sf) <- 4326

#get osm road data for bounding box
osm_roads_secondary_sf <- 
  opq(bbox = st_bbox(bbox_sf)) %>%
  add_osm_feature(key = 'highway', value = 'secondary') %>%
  osmdata_sf()

ggplot() + 
  geom_sf(data=osm_roads_secondary_sf$osm_lines,size=4)

road plot has gaps in it

session 信息:

R version 3.5.0 (2018-04-23)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.6

other attached packages:
 [1] osmdata_0.0.7        sf_0.6-3             forcats_0.3.0        
stringr_1.3.1       
 [5] dplyr_0.7.5          purrr_0.2.5          readr_1.1.1          
tidyr_0.8.1         
 [9] tibble_1.4.2         ggplot2_3.0.0        tidyverse_1.2.1.9000

最佳答案

理想的解决方案是将 lineend = "round" 传递给 geom_sf,它应该传递给 geom_path(它的底层,真的)来圆整线条的末端,导致轻微的重叠和平滑的外观。遗憾的是,这不起作用:

ggplot(osm_roads_secondary_sf$osm_lines) + 
    geom_sf(size = 4, lineend = "round")
#> Warning: Ignoring unknown parameters: lineend

我已经提交了 an issue在 GitHub 上,但由于 ggplot 刚刚发布,任何修复都不会在一段时间内到达 CRAN。

与此同时,解决方法包括使用 st_coordinates 从几何列中提取路径。生成的矩阵被强制转换为数据框,可以用 geom_path 绘制,它很乐意接受 lineend 参数:

osm_roads_secondary_sf$osm_lines %>% 
    st_coordinates() %>% 
    as.data.frame() %>% 
    ggplot(aes(X, Y, group = L1)) + 
    geom_path(size = 4, lineend = "round") + 
    coord_sf(crs = 4326)

将颜色更改为合适的灰色阴影以获得更像 geom_sf 的外观。

一种更 sf-native 的方法是将线段合并为连续的线,当然,这些线没有间隙。 st_line_merge 完成繁重的工作,但您需要事先将它们聚合成多行,以便它具有必要的数据:

osm_roads_secondary_sf$osm_lines %>% 
    st_union() %>% 
    st_line_merge() %>% 
    ggplot() + 
    geom_sf(size = 4)

请注意,这主要是更好,但并非完全如此。线条内的间隙消失了,但是 st_line_join 不知道如何修复三向交叉点,所以那里仍然有一个微小的间隙。如果您的真实数据有很多这样的交叉点(这是很有可能的),这种方法不会产生好的结果。

最后一种方法是简单地使用基本 sf 绘图,默认为圆形线端:

plot(osm_roads_secondary_sf$osm_lines$geometry, lwd = 10)

这种方法是否可行取决于绘图还有哪些工作要做,以及您对基本绘图的熟练程度。

关于r - 使用 ggplot2/geom_sf 绘图时修复 osm 道路中的间隙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51812311/

相关文章:

openstreetmap - Osmosis 不适用于 mapfilewriter 插件

python - 在 Python 中访问 R 用户定义的函数

SharePoint 中的 R

r - (function (classes, fdef, mtable) : unable to find an inherited method for function ‘select’ for signature ‘"spec_tbl_df"’ 中的错误

r - 如何在连续的颜色图例中添加一条线而不是情节?

R ggplot2错误: stacking not well defined when ymin! =0

R - 计算沿折线的两点之间的距离

r - 当 N 很小时,隐藏 geom_boxplot() 中的框和须线

android - 无法在 Android 手机上显示 OpenStreetMap

math - 缩放事件后计算 map 的新中心