Skip to content

Instantly share code, notes, and snippets.

@ramnathv
Created March 5, 2011 20:20
Show Gist options
  • Save ramnathv/856685 to your computer and use it in GitHub Desktop.
Save ramnathv/856685 to your computer and use it in GitHub Desktop.
# Find winner and percent of votes secured
candidates = names(df)[4:9];
df$winner = candidates[apply(df[, candidates], 1, which.max)];
df$winpct = apply(df[, candidates], 1, max);
# Assign palettes to winners
df$colpal = sapply(df$winner, switch,
'braun' = 'PuRd', 'chico' = 'Greens',
'delvalle' = 'Oranges', 'emanuel' = 'Purples');
# Bin winner's pct votes secured
df$bins = cut(df$winpct, c(0, 50, 75, 100),
labels = F, include.lowest = T);
# Choose fill colors
df = adply(df, 1, transform,
fillcol = brewer.pal(5, colpal)[bins + 2]);
# Plot choropleth
choro3 = plotChoropleth(.poly = chicago, .df = df,
id1 = list('WARD', 'PRECINCT'),
id2 = list('ward', 'precinct'),
fill = 'fillcol',
title = 'Chicago Mayoral Elections 2011',
legtitle = 'Pct Votes for Winner',
colpal = 'Blues', n = 5, style = 'pretty') +
opts(legend.position = c(0.15, 0.25))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment