Adam T. Bradley

Posts in tag “maps”

More mapping with R

One more map; I'm doing more experimenting with plotting data from multiple dataframes using ggplot2.

library(rjson)
library(RCurl)
library(ggplot2)
#The `whereIs` function polls [Google's geocoding API]
#(https://developers.google.com/maps/documentation
#/geocoding/) and returns the latitude and longitude of a
#place.
whereIs <- function(place) {
url = paste('http://maps.googleapis.com/maps/',
'api/geocode/json?sensor=false&address=',
curlEscape(place), sep='')
rs <- fromJSON(file=url)
c(rs$results[[1]]$geometry$location$lat,
rs$results[[1]]$geometry$location$lng)
}
new_england <- c('connecticut', 'rhode island',
'massachusetts', 'vermont',
'new hampshire', 'maine')
states <- map_data("state")
states.ne <- subset(states, region %in% new_england)
counties <- map_data('county')
counties.ne <- subset(counties, region %in% new_england)
capital <- c('Hartford', 'Providence',
'Boston', 'Montpelier',
'Concord', 'Augusta')
#Here we create a dataframe with info on state capitals,
#including location (from `whereIs()`) and population
#(copied manually from Wikipedia).
ne <- data.frame(capital, new_england,
stringsAsFactors=F)
geo <- sapply(do.call(paste, c(ne, sep=", ")), whereIs)
pop <- c(124775, 178042, 625087,
7855, 42695, 19136)
ne <- cbind(ne, pop, geo[1,], geo[2,])
rownames(ne) <- NULL
colnames(ne) <- c('capital','state','pop','lat','long')
map_theme <- theme(
line = element_blank(),
rect = element_blank(),
strip.text = element_blank(),
axis.text = element_blank(),
axis.title = element_blank(),
legend.position="none")
#Initialize a new `ggplot` plot.
plt <- ggplot() + map_theme +
ggtitle("New England counties and capitals") +
scale_fill_brewer(palette="Dark2")
#Draw the counties, outlining each with white. Make each
#state a different color (`fill=region`).
plt <- plt +
geom_polygon(data=counties.ne,
aes(long,lat,
group=group,
fill=region)) +
geom_path(data=counties.ne,
aes(long,lat,group=group),
colour="white")
#Add heavier white lines around the states. I tried some
#other methods, like black dotted/dashed lines, but
#didn't like them as much.
plt <- plt +
geom_path(data=states.ne,
aes(long,lat,group=group),
colour="white",linetype='solid', lwd=1.8)
#Add black dots for capitals, sized based on population.
plt <- plt +
geom_point(data=ne, colour='black',
aes(long, lat,
size=pop))
#Output the plot.
plt

plot of chunk unnamed-chunk-1