从ggplot地图上的osmar对象绘制道路
问题描述:
我已经使用ggplot代码(简化版本的代码)从我在中国的研究地点的栅格对象(来自worldclim的高程数据)创建了一个高程图。相关的栅格对象已从worldclim.org下载并使用栅格包转换为data.frame。这是用于此图的数据的link。从ggplot地图上的osmar对象绘制道路
# 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中? 还是有更好的解决方案比奥斯马包为我的目的?
答
可以fortify
的SpatialLinesDataFrame
,然后绘制与ggplot
fortify(hw_lines) %>%
ggplot(aes(x = long, y = lat, group = group)) +
geom_path()
的group
审美从加入所有的道路连成一个长行停止ggplot
。
谢谢,理查德。完美的工作。 – Aud