Rob Weyant bio photo

Rob Weyant

Data Scientist at Powerley

Twitter LinkedIn Instagram Github Last.fm

Basic Syntax

# Load Census Data
census_data_url <- 'http://www.bertplot.com/visualization/wp-content/uploads/2015/08/ACS_13_1YR_DP02_with_ann.csv'
census_data <- read.csv(census_data_url)
census_data$region = tolower(census_data$GEO.display.label)
census_data <- census_data %>% rename(born_in_us=HC03_VC132)
 
library(ggplot2)
# Load US State Coordinates
state_coords <- map_data("state")

# Join Census data with map data
state_data <- left_join(state_coords,
                       census_data,
                       by='region')

# Basic plot
map <- 
  ggplot(state_data) +
  geom_polygon(aes(x = long, y = lat,
                   group = group,
                   fill = born_in_us))
map

plot of chunk unnamed-chunk-1

Change Coordinate Projection

Requires installation of {mapproj} package

map+coord_map(project='conic',lat0=30)

plot of chunk unnamed-chunk-2

Aesthetics

Here we remove axes text and make legend text larger. We also remove the background so the only elements visible are the map and the legend

library(grid)

# Purely aesthetic changes
map_theme <- 
  theme(axis.ticks=element_blank(),
        axis.text.x=element_blank(),
        axis.text.y=element_blank(),
        axis.title.x=element_blank(),
        axis.title.y=element_blank(),
        legend.title=element_text(size=16),
        legend.text=element_text(size=12),
        legend.key.size=(unit(x=0.5,units='cm')),
        panel.background=element_rect(fill='white'))

map <- 
  ggplot(state_data) +
  geom_polygon(aes(x = long, y = lat,
                   group = group,
                   fill = born_in_us),
               color='black',           # Add an black outline to the states
               size=0.4) +
  coord_map(project='conic',lat0=30)+
  scale_fill_gradient('% Born in US')+  # Change Legend Label
  map_theme
map  

plot of chunk unnamed-chunk-3

More Resources