Plot map with values for countries as color in R?

rnso picture rnso · Jun 10, 2014 · Viewed 19.7k times · Source

I have following simple example data which I want to plot on a map with gradient color corresponding to value of the given country.

ddf = read.table(text="
country value
USA 10
UK 30
Sweden 50
Japan 70
China 90
Germany 100
France 80
Italy 60
Nepal 40
Nigeria 20
", header=T)

On google search, I found several sites. However, I am looking for code which is small and clear, and should preferably be fast (I found ggplot methods to be relativley slow). The resolution of world map need not be high.

I tried following code:

library(maptools)
data(wrld_simpl)
plot(wrld_simpl)

Specific nations can be colored as given on : Using [R] maps package - colouring in specific nations on a world map Using the command:

plot(wrld_simpl, col = c(gray(.80), "red")[grepl("^U", wrld_simpl@data$NAME) + 1])

But how can I get map with above data in a gradient of colors. Thanks for your help.

Answer

Andy picture Andy · Jun 10, 2014

You could use rworldmap if you wanted less code and a coarser resolution map.

library(rworldmap)

#create a map-shaped window
mapDevice('x11')
#join to a coarse resolution map
spdf <- joinCountryData2Map(ddf, joinCode="NAME", nameJoinColumn="country")

mapCountryData(spdf, nameColumnToPlot="value", catMethod="fixedWidth")

Default categorisation, colours and legends can be altered, see this RJournal paper.

It would be faster with country codes rather than names.

rworldmap map