In [5]:
# Based on example from http://matplotlib.org/examples/api/barchart_demo.html
# Data collected from NY Times, 5:06PM, 29 Nov 2016 for 2016
# http://www.nytimes.com/elections/results/president
# Other election results taken from Wikipedia articles about each U.S. Presidential Election
# e.g. https://en.wikipedia.org/wiki/United_States_presidential_election,_2000
# By R. Stuart Geiger, released CC0 (https://creativecommons.org/publicdomain/zero/1.0/)
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tkr
N = 5
demVotes = (50999897, 59028444, 69498516, 65915795, 64817808)
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars
fig, ax = plt.subplots(figsize=(8,4))
rects1 = ax.bar(ind, demVotes, width, color='b')
repVotes = (50456002, 62040610, 59948323, 60933504, 62510659)
rects2 = ax.bar(ind + width, repVotes, width, color='r')
# add some text for labels, title and axes ticks
ax.set_ylabel('Popular vote')
ax.set_title('Popular vote counts for presidential elections')
ax.set_xticks(ind + width)
ax.set_xticklabels(('2000', '2004', '2008', '2012', '2016'))
ax.legend((rects1[0], rects2[0]), ('Democratic candidate', 'Republican candidate'), loc=3)
# From http://stackoverflow.com/questions/8271564/matplotlib-comma-separated-number-format-for-axis/8272640
def func(x, pos): # formatter function takes tick label and tick position
s = '%d' % x
groups = []
while s and s[-1].isdigit():
groups.append(s[-3:])
s = s[:-3]
return s + ','.join(reversed(groups))
y_format = tkr.FuncFormatter(func) # make formatter
ax.yaxis.set_major_formatter(y_format) # set formatter to needed axis
plt.show()
plt.savefig("pop-vote-counts.png")
In [ ]: