Aug 20, 2012

Random graphs (2); Plotting country choropleths in R

 

 Steps in Stata

1) Create aggregate data set, for instance like this:
table cntry, c(mean sclmeet mean disc mean sclact) format (%9.4f)

2) Copy and paste resulting table to text editor or Excel to create a .csv file that can be used in R. Make sure that it's really comma-separated values, as in:
AT,4.6401,0.8263,2.7099
BE,4.8975,0.8292,2.5453
...
3) Also, add a header line in the first line of the file, so that it looks like:
Country,sclmeet,disc,sclact
AT,4.6401,0.8263,2.7099
BE,4.8975,0.8292,2.5453
...

4) Give it a name, for instance 'socialcontacts.csv,' and save it somewhere.

 

Steps in R

5) Open R. Install -rworldmaps-.
6) Set your working directory to where the data is and where you will save everything.
setwd("D:/YourDirectory/WhereTheDataIs")
7) Read in data and give it a name (here: "Meetsoc')
Meetsoc <-read.table("socialcontacts.csv", header=TRUE, sep=",")
attach(Meetsoc) # attach the data
names(Meetsoc) # give it names
Meetsoc[1:5,] # look at first 5 lines to see if it worked
8) Load 'rworldmap.'
library(rworldmap)
9) Join data to map and give it some name (here: 'MA1B')
MA1B <- joinCountryData2Map(Meetsoc, joinCode = "ISO2",
nameJoinColumn = "Country")
10) Produce map. xlim and ylim are the longitude and latitude. Missing country and ocean colors can be changed however one likes them.
# First map
par(mai = c(0, 0, 0.2, 0), xaxs = "i", yaxs = "i")

mapCountryData(MA1B, xlim=c(-15,29), ylim=c(40,70),
nameColumnToPlot = "sclmeet", catMethod = "categorical",
mapTitle = "Frequency of social meetings", colourPalette = "heat",
oceanCol = "lightblue", missingCountryCol = "white", borderCol =
"black", addLegend = F)

# Second map
par(mai = c(0, 0, 0.2, 0), xaxs = "i", yaxs = "i")

mapCountryData(MA1B, xlim=c(-15,29), ylim=c(40,70),
nameColumnToPlot = "disc", catMethod = "categorical",
mapTitle = "Prevalence of discussion partners",
colourPalette = "heat", oceanCol = "lightblue",
missingCountryCol = "white", borderCol = "black", addLegend = F)

# Third map
par(mai = c(0, 0, 0.2, 0), xaxs = "i", yaxs = "i")

mapCountryData(MA1B, xlim=c(-15,29), ylim=c(40,70),
nameColumnToPlot = "sclact", catMethod = "categorical",
mapTitle = "Frequency of social activities", 
colourPalette = "heat", oceanCol = "lightblue",
missingCountryCol = "white", borderCol = "black", addLegend = F)