A few weeks ago I wrote a post sharing some code I wrote to generate sharp-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":
To use this, first get the code via
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 and country 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.
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 at April 15, 2008 3:01 PM