如何使用ggplot/ggmap在SpatialLinesDataFrame中绘制和着色街道?

mas*_*don 5 plot r spatial ggplot2 ggmap

我有一个包含科隆所有街道的shapefile(SpatialLinesDataFrame),可以从这里下载.我将此@data与来自外部源的数据合并.我如何绘制这些街道(如果可能在谷歌地图上使用ggmaps),以便每条街道都有不同的颜色(或厚度),具体取决于它的个别价值?

到目前为止,我已经这样做了:

shapefile <- readOGR(shapfile, "Strasse", stringsAsFactors=FALSE, 
encoding="latin-9")
shp <- spTransform(shapefile, CRS("+proj=longlat +datum=WGS84"))
Run Code Online (Sandbox Code Playgroud)

此时我在shp @ data数据框中添加了另一列,其中包含每条街道的特定值.然后我强化了shapefile,因此可以使用ggplot绘制:

shp$id <- rownames(shp@data)
shp.df <- as.data.frame(shp)
data_fort <- fortify(shp, region = "id")
data_merged <- join(data_fort, shp.df, by="id")
Run Code Online (Sandbox Code Playgroud)

当我使用geom_lines时,这些线看起来不太好并且不容易识别:

ggplot(data_merged, aes(x=long, y=lat,
                      group=group,
                      colour=values)) +
 geom_line()
Run Code Online (Sandbox Code Playgroud)

在这里,我看到可以转换shapefile,以便可以使用geom_segement(或者在这种情况下是修改后的函数"geom_segment2"),但随后会丢失我的街道特定值.

jlh*_*ard 4

因此,此代码从 shapefile 中获取 100 条最长的道路,在 (1,10) 上随机分配“值”,并根据值在科隆的谷歌光栅图像之上使用基于颜色的颜色进行绘制。

library(ggplot2)   
library(ggmap)          # for ggmap(...) and get_map(...)
library(rgdal)          # for readOGR(...)
library(plyr)           # for join(...)
set.seed(1)             # for reproducible example
setwd(" <directory with your shapefiles> ")
spl <- readOGR(dsn=".", "Strasse", encoding="latin-9")
spl <- spl[spl$SHAPE_LEN %in% tail(sort(spl$SHAPE_LEN),100),]
shp       <- spTransform(spl, CRS("+proj=longlat +datum=WGS84"))
shp.df    <- data.frame(id=rownames(shp@data),
                        values=sample(1:10,length(shp),replace=T),
                        shp@data, stringsAsFactors=F)

data_fort   <- fortify(shp)
data_merged <- join(data_fort, shp.df, by="id")

ggmap(get_map(unlist(geocode("Cologne")),zoom=11))+
  geom_path(data=data_merged,size=1,
            aes(x=long,y=lat,group=group,color=factor(values)))+
  labs(x="",y="")+
  theme(axis.text=element_blank(),axis.ticks=element_blank())
Run Code Online (Sandbox Code Playgroud)

可以使用ggmap(...)以下命令使调用更简单:

ggmap(get_map("Cologne"))
Run Code Online (Sandbox Code Playgroud)

但有一个问题:zoom=...参数的解释不同,我无法充分缩放地图。