 

#  Google Charts from R: Maps 

 





April 15, 2008

 

 

A few weeks ago I wrote [a post](http://www.iq.harvard.edu/blog/sss/archives/2008/04/google_charts_f.shtml#more) sharing [some code I wrote](http://people.fas.harvard.edu/~aeggers/googleplot.r) to generate sharp-looking PNG scatterplots from R using the [Google Chart API](http://code.google.com/apis/chart). 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](http://services.alphaworks.ibm.com/manyeyes/data/S2fqLEsOtha670UHUO4ME2~).) 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":

To use this, first get the code via  
`source("http://people.fas.harvard.edu/~aeggers/googlemap.r")`  
which loads in a function named `googlemap`, to which you pass

  
- **x**: a vector of data
  
- **codes**: a vector of state/country codes (see the list of standard [state](http://code.google.com/apis/chart/#state_codes) and [country](http://code.google.com/apis/chart/#iso_codes) codes),
  
- and **location** a region of the world ("africa", "asia", "europe", "middle\_east", "south\_america", "usa") or the whole world ("world")
  

  
and you get back a url that you can embed in html as I did above, send over IM, etc. If you pass a **file** argument, as I did above, you can save the PNG locally.For optional parameters to affect the scale of the figure and its colors, see [the source](http://people.fas.harvard.edu/~aeggers/googlemap.r).

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")`

returns this url

`"http://chart.apis.google.com/chart?cht=t&chtm=africa . . . ` etc.

and saves this PNG on your hard drive:

The scatterplot thing before was something of a novelty, but I think this mapping functionality could actually be useful for generating quick maps in R, since the existing approaches are pretty annoying in my (limited) experience. The Google Charts API is not very flexible about labels and whatnot, so you probably won't be publishing any of these figures. But I expect this will serve very well for quick exploratory stuff, and I hope others do too.

I'd love it if someone wanted to help roll this into a proper `R` package . . . .

Posted by [Andy Eggers](http://www.iq.harvard.edu/blog/sss/archives/author/andy-eggers/) at April 15, 2008 3:01 PM



 

 

 



 

 

 Share on:- [     Facebook ](#)
- [     Twitter ](#)
- [     Linkedin ](#)