Home > OS >  How to select a value according to their spatial position?
How to select a value according to their spatial position?

Time:10-19

I would like to display the name of the countries in the center of each of those present on the output map. Is this possible directly from the word variable?

library(sp)

names(world)

saudi = world[world$name_long == "Saudi Arabia", ]
plot(st_geometry(saudi), expandBB = c(0, 0.2, 0.1, 1), col = "gray", lwd = 2)
plot(world[0], add = TRUE)

enter image description here

I would just like this case:

enter image description here

CodePudding user response:

library(tidyverse)

data <-
  map_data("world") %>%
  as_tibble() %>%
  filter(region %in% c("United Arab Emirates", "Saudi Arabia"))
data
#> # A tibble: 619 x 6
#>     long   lat group order region               subregion   
#>    <dbl> <dbl> <dbl> <int> <chr>                <chr>       
#>  1  53.9  24.2    11   959 United Arab Emirates Abu al Abyad
#>  2  53.9  24.1    11   960 United Arab Emirates Abu al Abyad
#>  3  53.8  24.2    11   961 United Arab Emirates Abu al Abyad
#>  4  53.8  24.1    11   962 United Arab Emirates Abu al Abyad
#>  5  53.7  24.1    11   963 United Arab Emirates Abu al Abyad
#>  6  53.6  24.2    11   964 United Arab Emirates Abu al Abyad
#>  7  53.7  24.2    11   965 United Arab Emirates Abu al Abyad
#>  8  53.8  24.3    11   966 United Arab Emirates Abu al Abyad
#>  9  53.9  24.2    11   967 United Arab Emirates Abu al Abyad
#> 10  53.9  24.2    11   968 United Arab Emirates Abu al Abyad
#> # … with 609 more rows

region_names <-
  data %>%
  group_by(region) %>%
  summarise(long = mean(long), lat = mean(lat))
region_names
#> # A tibble: 2 x 3
#>   region                long   lat
#>   <chr>                <dbl> <dbl>
#> 1 Saudi Arabia          44.9  23.2
#> 2 United Arab Emirates  54.4  24.3

data %>%
  ggplot(aes(long, lat))  
  geom_polygon(aes(color = region), fill = "white")  
  geom_text(
    data = region_names,
    mapping = aes(label = region)
  )

Created on 2021-10-18 by the enter image description here

CodePudding user response:

One very simple solution using tmap. Please find the reprex just below.

Reprex

library(sf)
#> Linking to GEOS 3.9.1, GDAL 3.2.1, PROJ 7.2.1
library(tmap)

data(World)
Saudi <-  World[World$name == "Saudi Arabia", ]

tm_shape(Saudi, bbox = st_as_sfc(st_bbox(c(st_bbox(Saudi)[1:2]*0.8,st_bbox(Saudi)[3:4]*1.2)))) 
  tm_fill("grey") 
  tm_borders(lty = "solid", lwd = 5, col = "black") 
  tm_text("name", size = 1.3) 
  tm_shape(World) 
  tm_borders(col = "black")

Created on 2021-10-18 by the reprex package (v2.0.1)

  • Related