Created
May 29, 2015 09:39
-
-
Save ayman/5a40f3bfb2f1833d04cd to your computer and use it in GitHub Desktop.
A cleaned up continuous solution for: http://stackoverflow.com/questions/24136868/plot-map-with-values-for-countries-as-color-in-r
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(RColorBrewer) | |
library(maptools) | |
library(ggplot2) | |
library(mapproj) | |
library(rgdal) | |
## make sure you call | |
gpclibPermit() | |
data(wrld_simpl) | |
ddf = read.table(text=" | |
country value | |
'United States' 10 | |
'United Kingdom' 30 | |
'Sweden' 50 | |
'Japan' 70 | |
'China' 90 | |
'Germany' 100 | |
'France' 80 | |
'Italy' 60 | |
'Nepal' 40 | |
'Nigeria' 20", header=TRUE) | |
pal <- colorRampPalette(brewer.pal(9, 'Reds'))(length(ddf$value)) | |
palSz <- 10 # Adjust for your desired range | |
wrld_simpl@data$id <- wrld_simpl@data$NAME | |
wrld <- fortify(wrld_simpl, region="id") | |
wrld <- subset(wrld, id != "Antarctica") # we don't rly need Antarctica | |
## start a blank plot | |
gg <- ggplot() | |
## setup base world map | |
gg <- gg + geom_map(data=wrld, | |
map=wrld, | |
aes(map_id=id, x=long, y=lat), | |
fill="white", | |
color="#7f7f7f", | |
size=0.25) | |
gg <- gg + geom_map(data=ddf, | |
map=wrld, | |
aes(map_id=country, fill=value), | |
color="white", | |
size=0.25) | |
gg <- gg + scale_fill_gradient2(low = pal[1], | |
mid = pal[palSz/2], | |
high = pal[palSz], | |
midpoint = (max(ddf$value) + min(ddf$value)) / 2, | |
name="value") | |
## this gives us proper coords. mercator proj is default | |
gg <- gg + coord_map() | |
gg <- gg + labs(x="", y="") | |
## if you want to hide the tick marks and background | |
gg <- gg + theme(plot.background = element_rect(fill = "transparent", colour = NA), | |
panel.border = element_blank(), | |
panel.background = element_rect(fill = "transparent", colour = NA), | |
panel.grid = element_blank(), | |
axis.text = element_blank(), | |
axis.ticks = element_blank(), | |
legend.position = "right") | |
(gg) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment