Options and packages:options(scipen = 999)
library(ggplot2)
library(maptools)
## Warning: package 'maptools' was built under R version 2.15.3
## Loading required package: foreign
## Loading required package: sp
## Warning: package 'sp' was built under R version 2.15.3
## Loading required package: grid
## Loading required package: lattice
## Checking rgeos availability: TRUE
library(hexbin)
## Warning: package 'hexbin' was built under R version 2.15.3
library(ggthemes)
## Warning: package 'ggthemes' was built under R version 2.15.3
library(rgeos)
## Warning: package 'rgeos' was built under R version 2.15.3
## rgeos version: 0.2-16, (SVN revision 389) GEOS runtime version:
## 3.3.6-CAPI-1.7.6 Polygon checking: TRUE
library(classInt)
## Warning: package 'classInt' was built under R version 2.15.3
## Loading required package: class
## Loading required package: e1071
library(RColorBrewer)
Loading and preparing the data:Read in the shapefile
USA <- readShapePoly("C:/CU BOULDER/Coursework/Y2S2/GEOG 5023 - Quant Methods Geo/Week 15 - ggplot2/USA copy.shp")
Clean and Summarize the data
USA <- USA[, c(1:8, 14:30)] #remove count fields
USA <- na.omit(USA) #remove missing data
Making Graphs with ggplot2:Visualize the data
plot1 <- ggplot(data = USA@data, aes(x = Obese, y = homevalu))
plot1 + geom_point()
plot1 + geom_point() + scale_x_log10() + scale_y_log10()
Add trasparency to address overplotting of points
plot1 + geom_point(alpha = 1/10) + scale_x_log10() + scale_y_log10()
plot1 + geom_point(alpha = 1/10) + geom_smooth(method = "lm") #add a fitted line
plot1 + geom_point(alpha = 1/10) + geom_smooth(method = "loess") #add a lowess curve
plot1 + stat_binhex() #deal with overplotting using hexogonal bins
plot1 + geom_bin2d() #deal with overplotting with regular bins
plot1 + geom_density2d() #try a density plot
Create a qualitative variable
USA$good_states <- ifelse(USA$STATE_NAME %in% c("New York", "Massachusetts",
"Rhode Island", "Wyoming"), yes = "its good", no = "its ok")
USA$good_states <- as.factor(USA$good_states)
Modify prior plots
plot2 <- ggplot(data = USA@data, aes(x = Obese, y = homevalu, color = good_states))
plot2 + geom_point()
plot2 <- ggplot(data = USA@data, aes(x = Obese, y = homevalu, color = good_states,
shape = good_states))
plot2 + stat_smooth() #use a local fit
## geom_smooth: method="auto" and size of largest group is >=1000, so using
## gam with formula: y ~ s(x, bs = "cs"). Use 'method = x' to change the
## smoothing method.
plot2 + geom_point() + stat_smooth(method = "lm", se = TRUE, lwd = 0.5, lty = 1)
# lwd controls line thickenss lty controls line type 1= solid line, higher
# numbers various forms of dashed lines. se can be used ti turn off the
# grey standaed error envelopes.
Add marginalia and change the appearance of the plots
# Look at the percent college educated (pctcoled) and the per capita
# income (pcincome), these two variables have a correlation of r=.7 so our
# plots should show some sort of relationship.
plot3 <- ggplot(data = USA@data, aes(x = pctcoled, y = pcincome))
plot3 + geom_point() + ylab("Per Capita Income") + xlab("Percent College Educated") +
ggtitle("US Counties (2000)\nPercent College Educated by Per Capita Income")
Make a multidimensional plot
# Add the unemployment variable to the plot by changing the color of the
# dots based on the unemployment rate.
plot4 <- ggplot(data = USA@data, aes(x = pctcoled, y = pcincome, color = unemploy)) +
geom_point() + ylab("Per Capita Income") + xlab("Percent College Educated") +
ggtitle("US Counties (2000)\nPercent College Educated by Per Capita Income") +
scale_color_gradient2("Unemployment", breaks = c(min(USA$unemploy), mean(USA$unemploy),
max(USA$unemploy)), labels = c("Below Average", "Average", "Above Average"),
low = "green", mid = "yellow", high = "red", midpoint = mean(USA$unemploy))
plot4
Split the plot into panels based upon the “good states” variable
# Create 'facets' or subplots that display only the data for each level of
# the factor.
plot4 + facet_grid(. ~ good_states)
# A more involved option:
plot4 + facet_grid(. ~ STATE_NAME)
Working with themes
plot4 + theme_classic()
# There is a library of themes:
plot4 + theme_economist()
plot4 + theme_solarized() #OUCH!
plot4 + theme_tufte()
# Seth's custom theme for presentations (with corrections in code to
# include plot title and legend title):
sethTheme <- theme(title = element_text(colour = "white"), panel.background = element_rect(fill = "black"),
plot.background = element_rect(fill = "black"), panel.grid.minor = element_blank(),
panel.grid.major = element_line(linetype = 3, colour = "white"), axis.text.x = element_text(colour = "grey80"),
axis.text.y = element_text(colour = "grey80"), axis.title.x = element_text(colour = "grey80"),
axis.title.y = element_text(colour = "grey80"), legend.key = element_rect(fill = "black"),
legend.text = element_text(colour = "white"), legend.title = element_text(colour = "white"),
legend.background = element_rect(fill = "black"), axis.ticks = element_blank())
plot4 + sethTheme
Making maps
# Use fortify to extract ploygon boundaries from the spatial Data Frame
# (its slow)
usa_geom <- fortify(USA, region = "FIPS")
dim(usa_geom)
## [1] 80926 7
# reattach data to ploygon boundaries
usa_map_df <- merge(usa_geom, USA, by.x = "id", by.y = "FIPS")
# make a map of bush_pct
map1 <- ggplot(usa_map_df, aes(long, lat, group = group)) + geom_polygon(data = usa_map_df,
aes(fill = Bush_pct)) + coord_equal() + scale_fill_gradient(low = "yellow",
high = "red") + geom_path(data = usa_geom, aes(long, lat, group = group),
lty = 3, lwd = 0.1, color = "white")
map1
map1 + sethTheme
Make thematic maps with legend classes using ColorBrewer
classIntervals(USA$Bush_pct, n = 5, style = "quantile")
## style: quantile
## [0,50.52) [50.52,58.07) [58.07,64.37) [64.37,71.31) [71.31,92.83]
## 622 622 622 622 623
breaks <- c(0, 50, 58, 64, 71, 93) #approximate quantiles
labels = c("[0 - 50%]", "[50% - 58%]", "[58% - 64%]", "[64% - 71%]", "[71% - 93%]")
usa_map_df$bushBreaks <- cut(usa_map_df$Bush_pct, breaks = breaks, labels = labels)
map2 <- ggplot(aes(long, lat, group = group), data = usa_map_df) + geom_polygon(data = usa_map_df,
aes(fill = bushBreaks)) + coord_equal()
map2
map2 + scale_fill_brewer("Votes for Bush in 2004 (%)", palette = "YlGnBu") +
sethTheme + ggtitle("Votes for Bush in 2004 (%)") + theme(plot.title = element_text(size = 24,
face = "bold", color = "white", hjust = 2))