R and Google Charts/Maps
First of all, whoever decided that naming anything with less than 3 or 4 characters had a serious lack of foresight in terms of database searching. If it wasn’t for the popularity of C/C++, finding resources on learning it would be nigh impossible. Well, slightly easier than R, one of the most commonly used letters of the alphabet. Google just looks at you funny when you search “R”; do the same thing with Python, Perl, Java, or any of the other languages with real names gets you solid results and excellent resources for learning. This has been a huge barrier for me, and I wish it would go away.
Anyway, Andy over at the Social Science Statistics Blog has been writing R to make use of the newly released Google API for making charts and such. Here is an update on his work:
Google Charts from R: Maps
A few weeks ago I wrote a post sharing some code I wrote to generate nice-looking PNG scatterplots from R using the Google Chart API. I think there are some nice uses of that (for example, as suggested by a commenter, to send a quick plot over IM), but here’s something that I think could be much more useful: maps from R using Google Charts.
So, suppose you have data on the proportion of people who say “pop” (as opposed to “soda” or “coke”) in each US state. (I got this data from Many-Eyes.) Once you get my code, you enter a command like this in R
googlemap(x = pct__who_say_pop, codes = state_codes, location = "usa", file ="pop.png")
and this image is saved locally as “pop.png”:
Details and another example after the jump.
So, in R, first get the code:
source("http://people.fas.harvard.edu/~aeggers/googlemap.r")
And then you pass in
- a vector of data
- a vector of state/country codes (see the list of standard state and country codes),
- and a location in the world (”africa”, “asia”, “europe”, “middle_east”, “south_america”, “usa”, “world”)
and you get back a url that you can embed in a website as I did above, send over IM, etc. If you pass a file argument, you can save the PNG locally.
For optional parameters to affect the scale of the figure and its colors, see the source.
Another quick example:
Suppose you wanted to make a little plot of Germany’s colonial possessions in Africa. This code
googlemap(x = c(1,1,1,1), location = "africa", codes = c("CM", "TZ", "NA", "TG"),file = "germans_in_africa.png")
which returns this url
"http://chart.apis.google.com/chart?cht=t&chtm=africa . . . etc.
and saves this PNG on your hard drive:
What makes this useful is that mapping in R is pretty painful, in my experience. The Google Charts API is not very flexible, so you probably won’t be publishing any of these figures. But for a first pass I think this is great and much easier than what you can currently do in R.
I’d love it if someone wanted to help roll this into a proper R package . . . .

