【问题标题】:Plotting roads from an osmar object on a ggplot map在 ggplot 地图上从 osmar 对象绘制道路
【发布时间】:2018-02-28 23:35:22
【问题描述】:

我使用 ggplot 代码(代码的简化版本)从我在中国的研究地点的栅格对象(来自 worldclim 的高程数据)创建了高程图。相关的栅格对象已从 worldclim.org 下载并使用 raster 包转换为 data.frame。这是用于此绘图的数据的link

# load library
library("tidyverse")
load(file = "gongga.RData")

ggplot() +
 geom_raster(data = gongga, aes(x=x, y=y, fill = elev)) +
 coord_equal() +
 scale_fill_gradient(name = "Elevation", low = "grey0", high = "grey100") + 
 scale_x_continuous(expand = c(0,0)) +
 scale_y_continuous(expand = c(0,0)) +
 theme(aspect.ratio=1/1, text = element_text(size=15))

为清楚起见,我想在地图上添加道路。我遇到了从 Openstreetmap 中提取道路的 osmar 包。

使用来自here 的代码,我为正确的路段提取道路,但我不知道如何将它们绘制到我现有的 ggplot 中。

# EXTRACT ROADS FROM OPENSTREETMAP AND PLOT THEM WITH RANDOM POINTS
# Load libraries
library('osmar')
library('geosphere')

# Define the spatial extend of the OSM data we want to retrieve
moxi.box <- center_bbox(center_lon = 102.025, center_lat = 29.875, 
width =  10000, height = 10000)

# Download all osm data inside this area
api <- osmsource_api()
moxi <- get_osm(moxi.box, source = api)

# Find highways
ways <- find(moxi, way(tags(k == "highway")))
ways <- find_down(moxi, way(ways))
ways <- subset(moxi, ids = ways)

# SpatialLinesDataFrame object
hw_lines <- as_sp(ways, "lines") 

# Plot points
plot(hw_lines, xlab = "Lon", ylab = "Lat")
box() 

对象是否需要任何转换才能在 ggplot 中绘制它? 或者对于我的目的,有比 osmar 包更好的解决方案吗?

【问题讨论】:

    标签: r ggplot2 openstreetmap raster osmar


    【解决方案1】:

    你可以fortify SpatialLinesDataFrame 然后用ggplot 绘制它

    fortify(hw_lines) %>% 
      ggplot(aes(x = long, y = lat, group = group)) + 
      geom_path()
    

    group 美学阻止ggplot 将所有道路连接成一条长线。

    【讨论】:

    • 谢谢,理查德。工作得很好。
    猜你喜欢
    • 1970-01-01
    • 2021-10-09
    • 2021-06-15
    • 2020-09-26
    • 2021-08-14
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多