In [2]:
from datetime import datetime
import os
import pyopenstates
import sys
def get_state_abbr(state):
return state.get('abbreviation')
def get_state_name(state):
return state.get('name')
def query_state(state, search_terms):
"""
https://openstates.github.io/pyopenstates/pyopenstates%20module.html#pyopenstates.search_bills
uses keyworded argument in function
"""
print('Query for ' + state + ' bills')
bills = pyopenstates.search_bills(state=state, q=search_terms)
return bills
In [3]:
pyopenstates.set_api_key(KEY HERE)
metadata = pyopenstates.get_metadata()
states = list(map(get_state_abbr, metadata))
In [4]:
search = 'firearms'
states_bills_firearms = {}
for state in states:
bills = query_state(state, search)
states_bills_firearms[state] = bills
In [5]:
# create dictionary with key of state abbr and value of number of bills
bill_count_by_state = {}
for state in states:
bill_count_by_state[state] = len(states_bills_firearms[state])
print(bill_count_by_state)
In [6]:
# create array of number of bills
values = list(bill_count_by_state.values())
values.sort()
print(values)
# count all bills
total_bills = 0
for value in values:
total_bills = total_bills + value
print(total_bills)
In [7]:
# create dictionary of with key as state abbr and value as name
state_names = {}
for state in metadata:
state_names[state.get('abbreviation')] = state.get('name')
print(state_names)
len(state_names)
Out[7]:
In [8]:
# output dictonary where key is state name and value is number of bills for map
bill_count_by_state_name = {}
for state in states:
bill_count_by_state_name[state_names[state]] = bill_count_by_state[state]
print(bill_count_by_state_name)
In [9]:
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap as Basemap
from matplotlib.colors import rgb2hex
from matplotlib.patches import Polygon
# https://stackoverflow.com/questions/39742305/how-to-use-basemap-python-to-plot-us-with-50-states
# Hawaii has 8 main islands but several tiny atolls that extend for many miles.
# This is the area cutoff between the 8 main islands and the tiny atolls.
ATOLL_CUTOFF = 0.005
m = Basemap(llcrnrlon=-121,llcrnrlat=20,urcrnrlon=-62,urcrnrlat=51,
projection='lcc',lat_1=32,lat_2=45,lon_0=-95)
# draw state boundaries.
# data from U.S Census Bureau
# http://www.census.gov/geo/www/cob/st2000.html
shp_info = m.readshapefile('st99_d00','states',drawbounds=True)
# print(shp_info)
# choose a color for each state based on population density.
# Map with Hawaii and Alaska
colors={}
statenames=[]
cmap = plt.cm.hot # use 'hot' colormap
vmin = 0; vmax = 450 # set range.
# print(m.states_info[0].keys())
for shapedict in m.states_info:
statename = shapedict['NAME']
# skip DC and Puerto Rico.
if statename not in ['District of Columbia','Puerto Rico']:
pop = bill_count_by_state_name[statename]
# calling colormap with value between 0 and 1 returns
# rgba value. Invert color range (hot colors are high
# population), take sqrt root to spread out colors more.
colors[statename] = cmap(1.-np.sqrt((pop-vmin)/(vmax-vmin)))[:3]
statenames.append(statename)
# cycle through state names, color each one.
ax = plt.gca() # get current axes instance
for nshape,seg in enumerate(m.states):
# skip DC and Puerto Rico.
if statenames[nshape] not in ['District of Columbia','Puerto Rico']:
# Offset Alaska and Hawaii to the lower-left corner.
if statenames[nshape] == 'Alaska':
# Alaska is too big. Scale it down to 35% first, then translate it.
seg = list(map(lambda s: (0.35*s[0] + 1100000, 0.35*s[1]-1300000), seg))
if statenames[nshape] == 'Hawaii':
seg = list(map(lambda s: (s[0] + 5200000, s[1]-1400000), seg))
color = rgb2hex(colors[statenames[nshape]])
poly = Polygon(seg, facecolor=color, edgecolor='black', linewidth=.5)
ax.add_patch(poly)
plt.title('Bills with keyword "firearms"')
plt.show()
In [10]:
tx = states_bills_firearms['tx']
print(tx[0])
In [11]:
bill_count_by_state.get('tx')
Out[11]:
In [ ]: