Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using [R] maps package - colouring in specific nations on a world map

Tags:

r

maps

I'm trying to create a world map and color certain nations. Basically, I would like to highlight some countries in red and other countries in blue.

If someone could help me generate the basic [R] code for this, I would be very thankful!!

like image 340
user1182741 Avatar asked Feb 01 '12 13:02

user1182741


People also ask

What is the maps package in R?

The maps package contains a lot of outlines of continents, countries, states, and counties that have been with R for a long time. The mapdata package contains a few more, higher-resolution outlines. The maps package comes with a plotting function, but, we will opt to use ggplot2 to plot the maps in the maps package.


Video Answer


1 Answers

If you are not hooked on using the maps package, the object wrld_simpl in the maptools package can make producing this sort of map pretty easy. Here, to get you started, are a few lines of code that produce a world map in which nations whose names start with the letter "U" are colored in red:

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

(wrld_simpl is an object of class SpatialPolygonsDataFrame, and the data.frame contained in wrld_simple@data includes a NAME column that you can use to highlight whichever countries you choose.)

enter image description here

like image 190
Josh O'Brien Avatar answered Nov 18 '22 12:11

Josh O'Brien