Color coded map using ggplot2

I am trying to create a generate world map plot where the color of each country corresponds to a specific value stored in the dataframe.

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

      

Here 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

      

This renders the world map well, so I want to add color to each country in proportion to the num_responses value in aggregated_country_data p>

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 is color-coding each of the colors as they correspond to the country code, not the value that is in the num_responses column in aggregated_country_data.

It is clear that there is something about ggplot2 that I am not getting, but I cannot figure out what it is.

Any input would be grateful, Brad


I figured out what the problem was and it has nothing to do with ggplot2 or anything else I was doing. The aggregated_country_data data frame has different names for "region" than in map.world. My original data (aggregated_country_data) defaults to a two-letter country code, which I have converted to a country name (called "area" in the data frame) using the Rode countrycode package, but uses a different naming convention than the one in map.world. So that's a completely different problem.

+3


source to share


1 answer


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

+7


source







All Articles