新十岁上下sf
包的R使得它很容易处理R中 地理数据,并ggplot2
的发展探析版本有一个新的 geom_sf()
层密谋SF风格的地理数据。地图美学中的R与SF LINESTRING几何
内sf
模式处理数据的,是有可能 ggplot aestheics映射到LINESTRING
几何?
例如,标准ggplot,有可能重新Minard's famous plot of survivors from Napoleon's Grande Armée in 1812 与ggplot和this data,幸存者的数量上浆军队的路径 :
# Install the dev version of ggplot2 for geom_sf()
# devtools::install_github("tidyverse/ggplot2")
library(tidyverse)
troops <- read_csv("https://gist.githubusercontent.com/andrewheiss/69b9dffb7cca392eb7f9bdf56789140f/raw/3e2a48635ae44837955765b5e7747c429b0b5d71/troops.csv")
ggplot(troops) +
geom_path(aes(x = long, y = lat, color = direction,
group = group, size = survivors),
lineend = "round")
我们可以工作通过创建新的 geometry
列将此部队数据作为sf
对象,如下所示:
library(sf)
#> Linking to GEOS 3.6.1, GDAL 2.1.3, proj.4 4.9.3
troops_with_geometry <- troops %>%
st_as_sf(coords = c("long", "lat"))
head(troops_with_geometry)
#> Simple feature collection with 6 features and 3 fields
#> geometry type: POINT
#> dimension: XY
#> bbox: xmin: 24 ymin: 54.5 xmax: 28 ymax: 55
#> epsg (SRID): NA
#> proj4string: NA
#> # A tibble: 6 x 4
#> survivors direction group geometry
#> <int> <chr> <int> <simple_feature>
#> 1 340000 A 1 <POINT (24 54.9)>
#> 2 340000 A 1 <POINT (24.5 55)>
#> 3 340000 A 1 <POINT (25.5 ...>
#> 4 320000 A 1 <POINT (26 54.7)>
#> 5 300000 A 1 <POINT (27 54.8)>
#> 6 280000 A 1 <POINT (28 54.9)>
如果我们geom_sf
绘制这个,ggplot将使用要点:
ggplot(troops_with_geometry) +
geom_sf(aes(color = direction, group = group))
我们可以通过 分组创建各团体和方向的线串,总结和铸造。然后
troops_lines <- troops_with_geometry %>%
group_by(direction, group) %>%
summarize() %>%
st_cast("LINESTRING")
head(troops_lines)
#> Simple feature collection with 6 features and 2 fields
#> geometry type: LINESTRING
#> dimension: XY
#> bbox: xmin: 24 ymin: 54.1 xmax: 37.7 ymax: 55.8
#> epsg (SRID): NA
#> proj4string: NA
#> direction group geometry
#> 1 A 1 LINESTRING (24 54.9, 24.5 5...
#> 2 A 2 LINESTRING (24 55.1, 24.5 5...
#> 3 A 3 LINESTRING (24 55.2, 24.5 5...
#> 4 R 1 LINESTRING (24.1 54.4, 24.2...
#> 5 R 2 LINESTRING (28.3 54.2, 28.5...
#> 6 R 3 LINESTRING (24.1 54.4, 24.2...
ggplot可以绘制这六个连接线和正确它们上色:
ggplot(troops_lines) +
geom_sf(aes(color = direction, group = group))
然而,幸存者数据已经没了,有没有办法大小 美学映射到新的线路。
有没有办法将其他美学(如大小)与sf
联系起来 LINESTRING
数据?或换句话说,有没有办法用geom_sf()
和使用地理数据的SF范式来重新创建 ggplot(...) + geom_path(aes(x = long, y = lat, size = something))
?
'geom_sf'似乎只在ggplot2的开发版本中可用(https://github.com/ropensci/seaaroundus/issues/24)。我必须从github('devtools :: install_github(“tidyverse/ggplot2”)')进行安装才能复制。 – mkearney
哦,是的。你需要开发版本:) – Andrew