繁体   English   中英

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

[英]How to plot and colour streets in a SpatialLinesDataFrame with ggplot/ggmap?

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

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

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

此时我在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")

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

ggplot(data_merged, aes(x=long, y=lat,
                      group=group,
                      colour=values)) +
 geom_line()

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

因此,此代码从您的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())

使用例如,可以使ggmap(...)调用更简单

ggmap(get_map("Cologne"))

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM