Created
September 9, 2020 01:52
-
-
Save dfuller22/8d3070ea46f769c614192ea40cd5adda to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def cand_per_yr_viewer(party_dict, yr_start='1920', yr_end=None, bar_width=0.15, figsize_=(10,7), keep=False): | |
import matplotlib.pyplot as plt | |
import numpy as np | |
## This code was heavily influenced by that found at: | |
# https://matplotlib.org/3.1.0/gallery/lines_bars_and_markers/barchart.html | |
## Setting dictionaries for label positioning | |
ha = {'center': 'center', 'right': 'left', 'left': 'right'} | |
offset = {'center': 0, 'right': 1, 'left': -1} | |
xpos = 'center' | |
## Helper lists to set plotting order + distances from centerpoint | |
party_list = ['R', 'D', 'T', 'S', 'I'] | |
bar_list = [(-1.5*bar_width), (-bar_width/2), (bar_width/2), (1.5*bar_width), (2.5*bar_width)] | |
## Containers to help with plotting | |
series_holder = [] | |
rect_holder = [] | |
## Edge case control | |
if int(yr_start) > 2006: | |
party_list = ['R', 'D', 'T', 'I'] | |
## Loops in order of party_list + grabs groupby series | |
for party in party_list: | |
series = party_dict[party].copy() | |
## Checks for ending year to slice + slices | |
if yr_end: | |
series_holder.append(series.loc[yr_start:yr_end]) | |
else: | |
series_holder.append(series.loc[yr_start:]) | |
## Setting figsize for plot | |
fig, ax = plt.subplots(figsize=figsize_) | |
## Aranging numbers to plot each series' values upon + width adjustment | |
for series, bar, party in zip(series_holder, bar_list, party_list): | |
ind_ = np.arange(len(series.index)) | |
rects = ax.bar(ind_ + bar, series, bar_width, label=party) | |
## Adding labels to each bar (rect) in the plot | |
for rect in rects: | |
height = rect.get_height() | |
ax.annotate('{}'.format(height), | |
xy=(rect.get_x() + rect.get_width() / 2, height), | |
xytext=(offset[xpos]*3, 3), textcoords="offset points", | |
ha=ha[xpos], va='bottom') | |
## Storing plot | |
rect_holder.append(rects) | |
## Formatting axes and setting title/legend | |
ax.set_ylabel('# of Candidates Running') | |
ax.set_xlabel('Year') | |
ax.set_title(f'# of Candidates by Year: {yr_start}-{yr_end}') | |
ax.set_xticks(np.arange(len(series_holder[0].index))) | |
ax.set_xticklabels(series_holder[0].index) | |
ax.legend() | |
fig.tight_layout() | |
## Display results! | |
plt.show() | |
## Optional storage of series and plots | |
if keep: | |
res_dict = {} | |
res_dict['series'] = series_holder | |
res_dict['rects'] = rect_holder | |
return res_dict |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment