在ggplot地图上绘制osmar对象的道路

时间:2017-09-20 03:56:59

标签: r ggplot2 openstreetmap raster osmar

我使用ggplot代码(代码的简化版本)从我在中国的研究地点的栅格对象(来自worldclim的高程数据)创建了一个高程图。已从worldclim.org下载相关的栅格对象,并使用栅格包将其转换为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))

Picture of the map created in ggplot

为了清楚起见,我想在地图上添加道路。我遇到了从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包更好的解决方案?

1 个答案:

答案 0 :(得分:1)

您可fortify SpatialLinesDataFrame然后用ggplot

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

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