In [46]:
%pylab inline
pylab.rcParams['figure.figsize'] = (20, 12)
import mpl_toolkits.basemap as bmp
import matplotlib.pyplot as plt
import csv
In [39]:
m = bmp.Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
projection='lcc',lat_1=33,lat_2=45,lon_0=-95)
plt.figure(figsize=(19,20))
Out[39]:
In [87]:
lon = []
lat = []
rad = []
seen = dict()
with open('data/raw_calc_lat_lon.csv', 'r') as csvfile:
tab = csv.reader(csvfile, delimiter=',')
for row in tab:
if row[1] != 'latitude':
if row[0] not in seen:
lat.append(float(row[1]))
lon.append(float(row[2]))
rad.append(float(row[3]) * 45)
seen[row[0]] = True
In [78]:
# Number of tweets
opacity = [389, 15, 334, 51, 739, 329, 86, 8, 0, 453, 339, 31, 47, 73, 302, 206, 71, 91, 22, 8, 298,
39, 9, 8, 30, 90, 10, 2, 5, 38, 122, 95, 96, 322, 0, 310, 140, 8, 62, 42, 123, 2, 164, 736, 65, 9,
54, 13, 22, 97, 2,]
In [84]:
colors = np.zeros((51,4))
colors[:,2] = 1.0
colors[:,3] = np.array(opacity)/(2*float((max(opacity)))) + 0.5
In [209]:
m.drawcoastlines(color='black')
m.drawstates(color='black')
m.drawcountries(color='black')
m.drawmapboundary(fill_color='white')
m.scatter(lon, lat, latlon=True, s=rad, c=colors)
plt.show()
In [88]:
plt.figure(figsize=(19,20))
Out[88]:
In [89]:
m.drawcoastlines(color='white')
m.drawstates(color='white')
m.drawcountries(color='white')
m.drawmapboundary(fill_color='black')
Out[89]:
In [98]:
states = {
'AK': 'Alaska',
'AL': 'Alabama',
'AR': 'Arkansas',
'AZ': 'Arizona',
'CA': 'California',
'CO': 'Colorado',
'CT': 'Connecticut',
'DC': 'District of Columbia',
'DE': 'Delaware',
'FL': 'Florida',
'GA': 'Georgia',
'HI': 'Hawaii',
'IA': 'Iowa',
'ID': 'Idaho',
'IL': 'Illinois',
'IN': 'Indiana',
'KS': 'Kansas',
'KY': 'Kentucky',
'LA': 'Louisiana',
'MA': 'Massachusetts',
'MD': 'Maryland',
'ME': 'Maine',
'MI': 'Michigan',
'MN': 'Minnesota',
'MO': 'Missouri',
'MS': 'Mississippi',
'MT': 'Montana',
'NC': 'North Carolina',
'ND': 'North Dakota',
'NE': 'Nebraska',
'NH': 'New Hampshire',
'NJ': 'New Jersey',
'NM': 'New Mexico',
'NV': 'Nevada',
'NY': 'New York',
'OH': 'Ohio',
'OK': 'Oklahoma',
'OR': 'Oregon',
'PA': 'Pennsylvania',
'RI': 'Rhode Island',
'SC': 'South Carolina',
'SD': 'South Dakota',
'TN': 'Tennessee',
'TX': 'Texas',
'UT': 'Utah',
'VA': 'Virginia',
'VT': 'Vermont',
'WA': 'Washington',
'WI': 'Wisconsin',
'WV': 'West Virginia',
'WY': 'Wyoming'
}
In [161]:
import pandas as pd
In [162]:
df = pd.DataFrame.from_csv('data/other/us_map_info.csv')
In [163]:
df[df['state'] == 'California']
Out[163]:
In [164]:
repwinners
Out[164]:
In [204]:
reppreds = dict()
dempreds = dict()
repwins = dict()
demwins = dict()
demmargins = dict()
repmargins = dict()
# rep_diff = dict()
# dem_diff = dict()
for state in states.values():
sub = df[df['state'] == state]
if len(sub.index) > 0:
# Predicted
hil_votes = sub.iloc[2]['predicted_votes_received']
ber_votes = sub.iloc[0]['predicted_votes_received']
dempreds[state] = 'Clinton'
if hil_votes < ber_votes:
dempreds[state] = 'Sanders'
print('%s \t Dem Pred Margin: %d' % (state, int(hil_votes - ber_votes)))
margin = hil_votes - ber_votes
trump_votes = sub.iloc[1]['predicted_votes_received']
kas_votes = sub.iloc[3]['predicted_votes_received']
ted_votes = sub.iloc[4]['predicted_votes_received']
rep_marg_tk = trump_votes - kas_votes
rep_marg_tt = trump_votes - ted_votes
rep_marg_kt = kas_votes - ted_votes
reppreds[state] = 'Trump'
if kas_votes > trump_votes:
reppreds[state] = 'Kasich'
elif ted_votes > trump_votes:
reppreds[state] = 'Cruz'
# Actual
hil_votes1 = sub.iloc[2]['actual_votes_received']
ber_votes1 = sub.iloc[0]['actual_votes_received']
demwins[state] = 'Clinton'
if hil_votes1 < ber_votes1:
demwins[state] = 'Sanders'
print('%s \t Dem Actual Margin: %d' % (state, int(hil_votes1 - ber_votes1)))
margin1 = hil_votes1 - ber_votes1
trump_votes = sub.iloc[1]['actual_votes_received']
kas_votes = sub.iloc[3]['actual_votes_received']
ted_votes = sub.iloc[4]['actual_votes_received']
repwins[state] = 'Trump'
if kas_votes > trump_votes:
repwins[state] = 'Kasich'
elif ted_votes > trump_votes:
repwins[state] = 'Cruz'
rep_marg_tk1 = trump_votes - kas_votes
rep_marg_tt1 = trump_votes - ted_votes
rep_marg_kt1 = kas_votes - ted_votes
print(hil_votes +ber_votes1)
demmargins[state] = abs((margin - margin1)/float(hil_votes1 + ber_votes1))
repmargins[state] = abs(((rep_marg_tk - rep_marg_tk1) + (rep_marg_tt - rep_marg_tt1) + (rep_marg_kt - rep_marg_kt1))/float(kas_votes +ted_votes +trump_votes))
In [167]:
demwins
Out[167]:
In [210]:
from matplotlib.patches import Polygon
# create the map
map = bmp.Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
projection='lcc',lat_1=33,lat_2=45,lon_0=-95)
# load the shapefile, use the name 'states'
map.readshapefile('state_shapes/st99_d00', name='states', color='black', drawbounds=True)
map.drawmapboundary(fill_color='white')
# collect the state names from the shapefile attributes so we can
# look up the shape obect for a state by it's name
state_names = []
for shape_dict in map.states_info:
state_names.append(shape_dict['NAME'])
ax = plt.gca() # get current axes instance
color_dict = {
'Sanders': 'teal',
'Clinton': 'blue',
'Trump': 'red',
'Kasich': 'orange',
'Cruz': 'purple',
}
for state in reppreds.keys():
seg = map.states[state_names.index(state)]
winner = reppreds[state]
poly = Polygon(seg, facecolor=color_dict[winner], edgecolor=color_dict[winner])
ax.add_patch(poly)
# get Texas and draw the filled polygon
# seg = map.states[state_names.index('Texas')]
# poly = Polygon(seg, facecolor='red',edgecolor='red')
# ax.add_patch(poly)
plt.show()
In [211]:
plt.figure(figsize=(19,20))
from matplotlib.patches import Polygon
# create the map
map = bmp.Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
projection='lcc',lat_1=33,lat_2=45,lon_0=-95)
# load the shapefile, use the name 'states'
map.readshapefile('state_shapes/st99_d00', name='states', color='black', drawbounds=True)
map.drawmapboundary(fill_color='white')
# collect the state names from the shapefile attributes so we can
# look up the shape obect for a state by it's name
state_names = []
for shape_dict in map.states_info:
state_names.append(shape_dict['NAME'])
ax = plt.gca() # get current axes instance
color_dict = {
'Sanders': 'teal',
'Clinton': 'blue',
'Trump': 'red',
'Kasich': 'orange',
'Cruz': 'purple',
}
for state in reppreds.keys():
seg = map.states[state_names.index(state)]
winner = repwins[state]
poly = Polygon(seg, facecolor=color_dict[winner], edgecolor=color_dict[winner])
ax.add_patch(poly)
# get Texas and draw the filled polygon
# seg = map.states[state_names.index('Texas')]
# poly = Polygon(seg, facecolor='red',edgecolor='red')
# ax.add_patch(poly)
plt.show()
In [212]:
plt.figure(figsize=(19,20))
from matplotlib.patches import Polygon
# create the map
map = bmp.Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
projection='lcc',lat_1=33,lat_2=45,lon_0=-95)
# load the shapefile, use the name 'states'
map.readshapefile('state_shapes/st99_d00', name='states', color='black', drawbounds=True)
map.drawmapboundary(fill_color='white')
# collect the state names from the shapefile attributes so we can
# look up the shape obect for a state by it's name
state_names = []
for shape_dict in map.states_info:
state_names.append(shape_dict['NAME'])
ax = plt.gca() # get current axes instance
color_dict = {
'Sanders': 'deepskyblue',
'Clinton': 'blue',
'Trump': 'red',
'Kasich': 'orange',
'Cruz': 'purple',
}
for state in reppreds.keys():
seg = map.states[state_names.index(state)]
winner = dempreds[state]
poly = Polygon(seg, facecolor=color_dict[winner], edgecolor=color_dict[winner])
ax.add_patch(poly)
# get Texas and draw the filled polygon
# seg = map.states[state_names.index('Texas')]
# poly = Polygon(seg, facecolor='red',edgecolor='red')
# ax.add_patch(poly)
plt.show()
In [213]:
plt.figure(figsize=(19,20))
from matplotlib.patches import Polygon
# create the map
map = bmp.Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
projection='lcc',lat_1=33,lat_2=45,lon_0=-95)
# load the shapefile, use the name 'states'
map.readshapefile('state_shapes/st99_d00', name='states', color='black', drawbounds=True)
map.drawmapboundary(fill_color='white')
# collect the state names from the shapefile attributes so we can
# look up the shape obect for a state by it's name
state_names = []
for shape_dict in map.states_info:
state_names.append(shape_dict['NAME'])
ax = plt.gca() # get current axes instance
color_dict = {
'Sanders': 'deepskyblue',
'Clinton': 'blue',
'Trump': 'orange',
'Kasich': 'red',
'Cruz': 'purple',
}
for state in reppreds.keys():
seg = map.states[state_names.index(state)]
winner = demwins[state]
poly = Polygon(seg, facecolor=color_dict[winner], edgecolor=color_dict[winner])
ax.add_patch(poly)
# get Texas and draw the filled polygon
# seg = map.states[state_names.index('Texas')]
# poly = Polygon(seg, facecolor='red',edgecolor='red')
# ax.add_patch(poly)
plt.show()
In [173]:
for key in demwins.keys():
print('%s \tpred: %s\tactual: %s, %r' % (key, dempreds[key], demwins[key], dempreds[key] == demwins[key]))
In [144]:
demwins
Out[144]:
In [193]:
min(demmargins.values())
Out[193]:
In [214]:
plt.figure(figsize=(19,20))
from matplotlib.patches import Polygon
# create the map
map = bmp.Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
projection='lcc',lat_1=33,lat_2=45,lon_0=-95)
# load the shapefile, use the name 'states'
map.readshapefile('state_shapes/st99_d00', name='states', color='black', drawbounds=True)
map.drawmapboundary(fill_color='white')
# collect the state names from the shapefile attributes so we can
# look up the shape obect for a state by it's name
state_names = []
for shape_dict in map.states_info:
state_names.append(shape_dict['NAME'])
ax = plt.gca() # get current axes instance
color_dict = {
'Sanders': 'deepskyblue',
'Clinton': 'blue',
'Trump': 'orange',
'Kasich': 'red',
'Cruz': 'purple',
}
for state in reppreds.keys():
seg = map.states[state_names.index(state)]
margin = (demmargins[state] - min(demmargins.values())) /(max(demmargins.values())-min(demmargins.values()))
poly = Polygon(seg, facecolor=[0, 0, 1, margin], edgecolor=[0, 0, 1, margin])
ax.add_patch(poly)
# get Texas and draw the filled polygon
# seg = map.states[state_names.index('Texas')]
# poly = Polygon(seg, facecolor='red',edgecolor='red')
# ax.add_patch(poly)
plt.show()
In [215]:
plt.figure(figsize=(19,20))
from matplotlib.patches import Polygon
# create the map
map = bmp.Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
projection='lcc',lat_1=33,lat_2=45,lon_0=-95)
# load the shapefile, use the name 'states'
map.readshapefile('state_shapes/st99_d00', name='states', color='black', drawbounds=True)
map.drawmapboundary(fill_color='white')
# collect the state names from the shapefile attributes so we can
# look up the shape obect for a state by it's name
state_names = []
for shape_dict in map.states_info:
state_names.append(shape_dict['NAME'])
ax = plt.gca() # get current axes instance
color_dict = {
'Sanders': 'deepskyblue',
'Clinton': 'blue',
'Trump': 'orange',
'Kasich': 'red',
'Cruz': 'purple',
}
for state in reppreds.keys():
seg = map.states[state_names.index(state)]
margin = (repmargins[state] - min(repmargins.values()))/(max(repmargins.values())-min(repmargins.values()))
poly = Polygon(seg, facecolor=[1, 0, 0, margin], edgecolor=[1, 0, 0, margin])
ax.add_patch(poly)
# get Texas and draw the filled polygon
# seg = map.states[state_names.index('Texas')]
# poly = Polygon(seg, facecolor='red',edgecolor='red')
# ax.add_patch(poly)
plt.show()
In [ ]: