Search code examples
rdictionaryggplot2geolocationrworldmap

filled map + location map in R


Rephrasing the question...I am preparing report and one part of it is spatial viz.

I have 2 datasets. First(Scores) is countries with their scores. Second one (Locations) is exact longitude and latitude that refers to an exact location inside those countries. Let that be examples:

Scores = data.frame( Country = c("Lebanon","UK","Chille"), Score =c(1,3.5,5))
Locations = data.frame(Location_Name = c("London Bridge", "US Embassy in Lebanon" , "Embassy of Peru in Santiago"),
                       LONG = c(-0.087749, 35.596614, -70.618236), 
                       LAT = c(51.507911, 33.933586, -33.423285))

What i want to achieve is get filled map of the world (in my dataset i have every country) and color inside of its boundouries with the Score (Scores$Score) on continous scale. On top of that I would like to add pins, bubbles or whatever marker of Locations from Locations dataframe.

So my desired outcome would be combination of this view: Filled map

and this view:

Location map

Ideally i would like also to be able to draw 2km radius around the Locations from Locations data.frame also.

I know to do them separately but cant seem to achieve it on one nice clean map.

I really appreciate any help or tips on this, got stuck for whole day on that one


Solution

  • As suggested by @agila you can use the tmap package.

    First merge your Scores data with World so you can fill countries based on Scores data. Note that your Country column should match the name in World exactly when merging.

    You will need to use st_as_sf from sf package to make your Locations an sf object to add to map.

    tm_dots can show points. An alternative for bubbles is tm_bubbles.

    library(tmap)
    library(sf)
    
    data(World)
    
    Scores = data.frame(Country = factor(c("Mexico","Brazil","Chile"), levels = levels(World$name)), 
                        Score =c(1,3.5,5))
    Locations = data.frame(Location_Name = c("Rio de Janeiro", "US Embassy in Lebanon" , "Embassy of Peru in Santiago"),
                           LONG = c(-43.196388, 35.596614, -70.618236), 
                           LAT = c(-22.908333, 33.933586, -33.423285))
    
    map_data <- merge(World, Scores, by.x = "name", by.y = "Country", all = TRUE)
    
    locations_sf <- st_as_sf(Locations, coords = c('LONG', 'LAT'))
    
    tm_shape(map_data) +
      tm_polygons("Score", palette = "-Blues") +
      tm_shape(locations_sf) +
      tm_dots(size = .1)
    

    Map

    world map with filled countries and points of interest