Skip to content

Instantly share code, notes, and snippets.

@stonemirror
Created February 21, 2018 05:31
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 stonemirror/2c9b822ae5f1c9ab44ef58d9d82cf295 to your computer and use it in GitHub Desktop.
Save stonemirror/2c9b822ae5f1c9ab44ef58d9d82cf295 to your computer and use it in GitHub Desktop.
Building a chart of gun law strictness v. gun death rates in Python...
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
#
# Read in the Brady Scores data, and extract the appropriate sheet into a DataFrame
#
workbook = pd.ExcelFile('Downloads/Brady-State-Scorecard-2014.xlsx')
dictionary = {}
for sheet_name in workbook.sheet_names:
df = workbook.parse(sheet_name)
dictionary[sheet_name] = df
scores = dictionary['scores rank']
#
# Read in the CDC data on gun-death rates
#
death_rate = pd.read_csv('Downloads/FIREARMS2016.csv', thousands=',')
#
# Merge the two dataframes
#
merged = scores.merge(death_rate, how='inner', left_on='ST', right_on='STATE')
#
# Plot the chart
#
fit = np.polyfit(merged['SCORE'], merged['RATE'], deg=1)
plt.figure(figsize=(10, 8))
plt.xlabel('Brady Center Score (higher is stricter)')
plt.ylabel('Guns Deaths per 100K Population')
plt.title('Gun Law Strictness vs. Rate of Gun Deaths')
plt.plot(merged['SCORE'], fit[0] * merged['SCORE'] + fit[1], color='red')
plt.scatter(merged['SCORE'], merged['RATE'], s=merged['DEATHS']/15.)
for i, txt in enumerate(merged['ST']):
plt.annotate(txt, (merged['SCORE'].iat[i], merged['RATE'].iat[i]))
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment