2014-07-15 91 views
5

我有一个shapefile(SpatialLinesDataFrame)包含科隆的所有街道,可以从here下载。我将这个@data与来自外部源的数据合并。我如何绘制这些街道(如果可能的话,在谷歌地图上使用ggmaps),以便每个街道都有不同的颜色(或厚度),具体取决于其个人价值?在这一点上我的另一列添加到SHP @数据的数据帧,其中包含每个街道一定值如何使用ggplot/ggmap在SpatialLinesDataFrame中绘制和着色街道?

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

到目前为止,我已经做到了这一点。然后我fortifiy的shape文件,因此它可以使用ggplot绘制:

shp$id <- rownames([email protected]) 
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() 

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

+0

你的shapefile似乎有> 5500条街道。你想让他们每个人都变成另一种颜色吗?另外,属性表没有'values'列。 – jlhoward

+0

我将@data与外部数据文件(我无法上传,因为隐私原因)相匹配。只有那些街道仍留在shapefile中,这些街道在我的原始数据文件中。然后我将外部文件中的值附加到shapefile @ data数据框。现在我意识到我可以上传修改后的shapefile文件,明天就可以做到这一点。值列在我的shapefile中,它包含从1-10开始的值,但是这是模拟的。当我使用geom_line()时,某些线条(街道)的某些部分充满了形状等颜色,你知道这是为什么吗? –

+0

对于初学者,您需要使用'geom_path(...)',而不是'geom_line(...)。 – jlhoward

回答

3

所以这段代码从你的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([email protected]), 
         values=sample(1:10,length(shp),replace=T), 
         [email protected], 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=...参数不同的解释,我没能充分放大地图。

相关问题