rggplot2geom-map

How to build world map in R and color selected countries


I'm trying to build a map showing a gradient of scores attributed to a selection of countries, these scores are stored in a dataframe (scores) alongside the corresponding country name:

Country Score
United States  0.4
France 0.2
India 0.6 etc.

I've tried the following (based on How do you get geom_map to show all parts of a map?) but get an error (Error in FUN(X[[i]], ...) : object 'region' not found)

world_map <- map_data('world')

gg <- ggplot(scores) +
 geom_map(dat = world_map, map = world_map, aes(map_id = region),
          fill = 'white', color = 'black' +
 geom_map(map = world_map, aes(map_id = region, fill = Score)

Grateful for any help as I can't seem to get anywhere with this.


Solution

  • Based on the question you linked, you should be calling upon Country and Score in your second geom_map call. Also there are a few parentheses missing from your code and please note that world_map uses "USA", not "United States".

    library(maps)
    library(tidyverse)
    scores <- read_table("
    Country Score
    USA  0.4
    France 0.2
    India 0.6")
    
    world_map <- map_data("world")
    gg <- ggplot(scores) + 
      geom_map(dat=world_map, map=world_map, 
                        aes(map_id=region), fill="white", color="black") + 
      geom_map(map=world_map, 
                        aes(map_id=Country, fill=Score), color="black") + 
      expand_limits(x = world_map$long, y = world_map$lat)
    gg
    

    enter image description here