Skip to content

Instantly share code, notes, and snippets.

@jackbandy
Created March 21, 2020 20:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackbandy/48d3a1268d25063e31e2fcd2dbe7449f to your computer and use it in GitHub Desktop.
Save jackbandy/48d3a1268d25063e31e2fcd2dbe7449f to your computer and use it in GitHub Desktop.
Based on Renzo Lucioni's famous senate voting graphs https://gist.github.com/rlucioni/8bdb1092579041ce739c
import re
import pandas as pd
import networkx as nx
import urllib.request
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.animation as animation
from textwrap import wrapk
def get_senate_vote(vote):
# Year can be replaced to fetch votes from different years (e.g., 2013). 1989 is used
# as an example.
csv_url= "https://www.govtrack.us/congress/votes/116-2020/s{}/export/csv".format(vote)
img_url= "https://www.govtrack.us/congress/votes/116-2020/s{}/diagram".format(vote)
try:
title=pd.read_csv(csv_url,nrows=1,header=None).at[0,0]
urllib.request.urlretrieve(img_url,'diagrams/vote-{}.png'.format(vote))
votes = pd.read_csv(csv_url,header=[1])
return title, votes
except ValueError:
raise Exception("Not a valid vote number.")
def get_all_votes():
vote_num = 1
vote_titles = []
vote_dfs = []
while True:
try:
title, votes = get_senate_vote(vote_num)
vote_titles.append(title)
vote_dfs.append(votes)
vote_num += 1
except Exception:
break
return vote_titles, vote_dfs
title_list, vote_dfs = get_all_votes()
fig = plt.figure()
ims = []
for i in range(len(title_list)):
vote_num=i+1
img = mpimg.imread('diagrams/vote-{}.png'.format(vote_num))
title = title_list[i]
top_title = title[:title.find('2020-')]
short_title = re.sub(" ?\([^)]+\)", "",title[title.find(' - ')+3:])
plt.imshow(img,animated=True)
plt.title("2020 {}".format(top_title),size=28)
#plt.title('\n'.join(wrap(short_title,32)),size=24)
plt.gca().set_xlabel('\n'.join(wrap(short_title,50)))
plt.savefig('diagrams/titled-vote-{}.png'.format(vote_num))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment