2017-09-20 73 views
1

我已經使用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)) 

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中? 還是有更好的解決方案比奧斯馬包爲我的目的?

回答

0

可以fortifySpatialLinesDataFrame,然後繪製與ggplot

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

group審美從加入所有的道路連成一個長行停止ggplot

+0

謝謝,理查德。完美的工作。 – Aud