Alex
Alex

Reputation: 163

Diagram with arranged countries polygons

I am looking for solution of a special diagram using following data set (below). The diagram has to contain the polygons of the countries from the data set, but they have to be (1) placed next to each other, not by long,lat coordinates; (2) the size of the polygon of the each country has to correspond to the relative size, which is a t$rs variable (calculated as it's shown below); (3) the fill color of each country depends on the value of t$value variable -- if it's positive the color is green and red if negative.

My code so far is:

 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,])
 

enter image description hereMy output diagram is attached. It's a bit far from desired shape.

Upvotes: 0

Views: 89

Answers (1)

mgrund
mgrund

Reputation: 1635

I adjusted your data import slightly using st_read() from the sf package:

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")

enter image description here

Upvotes: 1

Related Questions