【问题标题】:How to plot and colour streets in a SpatialLinesDataFrame with ggplot/ggmap?如何使用 ggplot/ggmap 在 SpatialLinesDataFrame 中绘制街道并为其着色?
【发布时间】:2014-09-05 19:31:07
【问题描述】:

我有一个包含科隆所有街道的 shapefile (SpatialLinesDataFrame),可以从 here 下载。我将此@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()

Here 我看到可以转换 shapefile,以便可以使用 geom_segment(或在本例中为修改后的函数“geom_segment2”),但随后会丢失我的街道特定值。

【问题讨论】:

  • 您的 shapefile 似乎有 >5500 条街道。你想让他们每个人都有不同的颜色吗?此外,属性表没有values 列。
  • 我将@data 与外部数据文件进行了匹配(出于隐私原因,我无法上传)。只有那些街道仍然留在 shapefile 中,在我的原始数据文件中。然后我将外部文件中的值附加到 shapefile@data 数据框。现在我意识到我可以上传修改后的 shapefile,明天会这样做。 values 列在我的 shapefile 中,它包含例如 1-10 的值,但这是模拟的。当我使用 geom_line() 时,某些线条(街道)的某些部分充满了类似形状的颜色,你知道这是为什么吗?
  • 对于初学者,您需要使用geom_path(...),而不是`geom_line(...)。
  • 只是在没有真实数据的情况下对其进行了测试,看起来好多了:) 谢谢。我还发现,不需要直接访问@data 框架,而是通过 shapefile 对象。

标签: r plot ggplot2 spatial ggmap


【解决方案1】:

因此,此代码从您的 shapefile 中抓取 100 条最长的道路,在 (1,10) 上随机分配“值”,并根据值在科隆的 google 光栅图像上绘制颜色。

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=... 参数的解释不同,我无法充分缩放地图。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 2020-04-14
    • 2012-10-30
    相关资源
    最近更新 更多