Plot colour coded world map using ggplot2

Brad Davis picture Brad Davis · Apr 28, 2015 · Viewed 12.9k times · Source

I am trying to generate a generate a plot of a world map where the colour of each country corresponds to a particular value stored in a data frame.

> aggregated_country_data
   country num_responses                                     region
1       AL             1                                    Albania
2       AM             1                                    Armenia
3       AR            32                                  Argentina
...
75      ZW             3                                   Zimbabwe

This is what I have tried

library(rworldmap)
library(ggplot2)
map.world <- map_data(map="world")

gg <- ggplot()
gg <- gg + theme(legend.position="none")
gg <- gg + geom_map(data=map.world, map=map.world, aes(map_id=region, x=long, y=lat), fill="white", colour="black", size=0.25)
gg

That plots the world map just fine, so next I want to add colour to each country in proportion to the value 'num_responses' in aggregated_country_data

gg <- gg + geom_map(data=aggregated_country_data, map=map.world, aes(map_id=region, fill=num_responses), color="white", size=0.25)
gg

But now it's colour coding each of the colours as they correspond to the country code rather than the value that's in the column num_responses in aggregated_country_data.

It's clear that there's something about ggplot2 that I'm not getting, but I can't figure out what that is.

I would appreciate any input, Brad


I figured out what the problem was, and it has nothing to do with ggplot2 or anything else that I was doing. The aggregated_country_data data frame has different names for 'region' than in map.world. My input data (aggregated_country_data) uses a two letter country code by default that I converted into country name (called 'region' in the data frame) using the countrycode R package, but it is using a different naming convention for the names than exists in map.world. So that's a totally different problem.

Answer

shekeine picture shekeine · Apr 28, 2015
library(rworldmap)
library(ggplot2)
map.world <- map_data(map="world")

#Add the data you want to map countries by to map.world
#In this example, I add lengths of country names plus some offset
map.world$name_len <- nchar(map.world$region) + sample(nrow(map.world))

gg <- ggplot()
gg <- gg + theme(legend.position="none")
gg <- gg + geom_map(data=map.world, map=map.world, aes(map_id=region, x=long, y=lat, fill=name_len))

gg <- gg + scale_fill_gradient(low = "green", high = "brown3", guide = "colourbar")
gg <- gg + coord_equal()
gg

enter image description here