【问题标题】:Diagram with arranged countries polygons带有排列国家多边形的图表
【发布时间】:2021-12-05 02:25:24
【问题描述】:

我正在寻找使用以下数据集(下)的特殊图表的解决方案。该图必须包含来自数据集的国家的多边形,但它们必须(1)彼此相邻放置,而不是长、纬度坐标; (2)每个国家的多边形的大小必须对应相对大小,这是一个t$rs变量(计算如下); (3) 每个国家的填充颜色取决于 t$value 变量的值 -- 如果为正则颜色为绿色,如果为负则为红色。

到目前为止我的代码是:

 library(ggmap)
 library(dplyr)
 library(sf) 
 library(tidyverse)
 library(gridExtra)
 library(rgdal)
 library(tmap)

 # The data set
 t <- data.frame(id    = c(136,142,172,567),
            name  = c("Italy","Norway","Finland","Singapore"),
            value = c(-0.921253632,245.6713064,4.049413648,207.5896534))

 # Min value in absolute terms
 min = min(abs(t$value))

 # Relative value w.r.t. min value 
 t$rs <- t$value / min

 # Shape files for countries
 # https://hub.arcgis.com/datasets/esri::world-countries-generalized/about

 # Unzip files from the ArcGIS archive file
 unzip("World_Countries_(Generalized).zip", exdir = ".")
 shp.file <- "World_Countries__Generalized_.shx"
 countries <- readOGR(shp.file)

 qtm(countries[countries$COUNTRY %in% t$name,])
 

我的输出图附后。距离想要的形状有点远。

【问题讨论】:

    标签: r ggplot2 plot shapefile tmap


    【解决方案1】:

    我使用 sf 包中的 st_read() 稍微调整了您的数据导入:

    library(tidyverse)
    library(sf)
    library(tmap)
    
    # Unzip files from the ArcGIS archive file
    unzip("World_Countries_(Generalized).zip", exdir = ".")
    shp.file <- "World_Countries__Generalized_.shx"
    countries <- st_read(shp.file) 
       
    countries %>% 
       left_join(t, by = c("COUNTRY" = "name")) %>% 
       filter(!is.na(id)) %>% 
       st_as_sf() %>% 
       tm_shape() + 
       tm_fill("value") +
       tm_facets(by = "COUNTRY")
    

    【讨论】:

    • 非常感谢!这让我进步了很多。有没有办法绘制这些不同大小国家的多边形?要使用的相对大小存储在变量t$rs中。
    • 根据可用的settings,无法按自定义值缩放单个多边形。这一步背后的意图是什么?
    • @mgrund 我同意你的看法。我以前也遇到过同样的问题,但我永远无法找到独立扩展每个方面的解决方案。我想这一定是可能的......