Ted Mosby Ted Mosby - 1 month ago 12
R Question

Color code countries using data in R and ggplot

I'm trying to plot a world map and fill in based on values. When I run the following code it seems to break the map. The map just looks odd and line-y for a lack of better terms. Map

What am I missing?

CODE & DATA

url='https://raw.githubusercontent.com/fivethirtyeight/data/master/alcohol-consumption/drinks.csv'
df = read.csv(url)

library(ggmap)
library(parallel)
# Get Lon and Lat for each country

countries = as.character(df$country)
df$region = df$country
coords = mclapply(X = countries,FUN= function(x) geocode(x))
coords=do.call(rbind.data.frame,coords)


library(RColorBrewer)
library(maptools)
library(ggplot2)
library(rworldmap)

map.world = map_data(map='world')
map.world = merge(df,map.world, by='region',all.y=TRUE )

gg = ggplot()
gg = gg + geom_map(data = map.world,map = map.world,
aes(map_id = region,x=long,y=lat,fill=map.world$beer_servings))
gg= gg+ scale_fill_gradient(breaks=c(500000,1000000,1500000),
labels=c("Low","Medium","High"))
gg = gg + coord_equal()
ggsave(filename = 'myplot.png',plot = gg)

Answer

I thing you have to reset the order after you merged your data:

url='https://raw.githubusercontent.com/fivethirtyeight/data/master/alcohol-consumption/drinks.csv'
df = read.csv(url)

library(RColorBrewer)
library(maptools)
library(ggplot2)
library(rworldmap)

map.world = map_data(map='world')
map.world = merge(df,map.world, by='region',all.y=TRUE)
map.world = map.world[order(map.world$order), ] # <---

ggplot() + 
  geom_map(data = map.world,map = map.world, aes(
    map_id = region,
    x=long,
    y=lat,
    fill=beer_servings
  )) + 
  coord_quickmap()

enter image description here