raf*_*ira 5 r geospatial ggplot2 tmap r-sf
我想使用ggplot2::geom_sf. 这里的挑战是如何做到这一点,使所有地图都在图像中居中并处于相同的空间尺度。这是问题(以下可重现示例的数据):
使用facet_wrap将所有多边形置于相同空间比例的简单地图,但它们不居中。
ggplot(states6) +
geom_sf() +
facet_wrap(~name_state)
Run Code Online (Sandbox Code Playgroud)
这是这个SO 问题的解决方案,
它使用cowplot. 在这种情况下,多边形居中,但它们处于不同的空间尺度
g <- purrr::map(unique(states6$name_state),
function(x) {
# subset data
temp_sf <- subset(states6, name_state == x)
ggplot() +
geom_sf(data = temp_sf, fill='black') +
guides(fill = FALSE) +
ggtitle(x) +
ggsn::scalebar(temp_sf, dist = 100, st.size=2,
height=0.01, model = 'WGS84',
transform = T, dist_unit='km')
})
g2 <- cowplot::plot_grid(plotlist = g)
g2
Run Code Online (Sandbox Code Playgroud)
我在使用tmap库时发现了同样的问题。
tm_shape(states6) +
tm_borders(col='black') +
tm_fill(col='black') +
tm_facets(by = "name_state ", ncol=3) +
tm_scale_bar(breaks = c(0, 50, 100), text.size = 3)
Run Code Online (Sandbox Code Playgroud)
我想得到的输出类似于以下内容:
library(sf)
library(geobr)
library(mapview)
library(ggplot2)
library(ggsn)
library(cowplot)
library(purrr)
library(tmap)
# Read all Brazilian states
states <- geobr::read_state(code_state = 'all', year=2015)
# Select six states
states6 <- subset(states, code_state %in% c(35,33,53,29,31,23))
Run Code Online (Sandbox Code Playgroud)
它 \xc2\xb4s 并不理想,但您可以使用相同的框大小以编程方式绘制多个图,然后使用::gridExtra将它们放在一起。要获取每个框的中心,请使用每个几何体的质心。
\n\nlibrary(sf)\nlibrary(geobr)\nlibrary(mapview)\nlibrary(ggplot2)\nlibrary(gridExtra)\nRun Code Online (Sandbox Code Playgroud)\n\n阅读巴西所有州:
\n\nstates <- geobr::read_state(code_state = \'all\', year=2015)\nRun Code Online (Sandbox Code Playgroud)\n\n选择六个州:
\n\nstates6 <- subset(states, code_state %in% c(35,33,53,29,31,23))\nRun Code Online (Sandbox Code Playgroud)\n\n质心,供下面的 ggplot 参考(我必须设置投影,如果需要,请在此处进行更改):
\n\nstates6$centroid <- \n sf::st_transform(states6, 29101) %>% \n sf::st_centroid() %>% \n sf::st_transform(., \'+proj=longlat +ellps=GRS80 +no_defs\') %>% \n sf::st_geometry()\nRun Code Online (Sandbox Code Playgroud)\n\n设置填充:
\n\npadding <-7 \nRun Code Online (Sandbox Code Playgroud)\n\n绘图函数:
\n\ngraph <- function(x){\n ggplot2::ggplot(states6[x,]) +\n geom_sf() +\n coord_sf(xlim = c(states6$centroid[[x]][1]-padding , \n states6$centroid[[x]][1]+padding), \n ylim = c(states6$centroid[[x]][2]-padding , \n states6$centroid[[x]][2]+padding), \n expand = FALSE)\n}\nRun Code Online (Sandbox Code Playgroud)\n\n创建一堆图:
\n\nplot_list <- lapply(X = 1:nrow(states6), FUN = graph)\nRun Code Online (Sandbox Code Playgroud)\n\n将它们网格在一起:
\n\ng <- cowplot::plot_grid(plotlist = plot_list, ncol = 3)\ng\nRun Code Online (Sandbox Code Playgroud)\n\n\n
| 归档时间: |
|
| 查看次数: |
1804 次 |
| 最近记录: |