import pandas as pd
import numpy as np
import os
import plotly.plotly as py
import plotly.graph_objs as go
import plotly
# Load judge ideology data and crosswalk between state names and codes
#judge_ideology_raw = pd.read_csv('Judge Attribute and Ideology.csv')
#state_geo = 'us-states.json'
#state_name_to_code = pd.read_csv('State Name to Code.csv')
dataDir = r'C:\Users\Ian\Dropbox\ECON 407 - US Courts & Judges'
judge_ideology_raw = pd.read_csv(os.path.join(dataDir,'Judge Attribute and Ideology.csv'))
state_name_to_code = pd.read_csv(os.path.join(dataDir,r'Mapping\State Name to Code.csv'))
# Clean judge ideology data and take only necessary columns
judge_ideology = judge_ideology_raw[['Name','State','Year of Appointment','Year of Departure','Ideology Score']]
judge_ideology = judge_ideology[judge_ideology['State'] != 'Puerto Rico']
judge_ideology = judge_ideology.merge(state_name_to_code, how = 'left')
judge_ideology = judge_ideology[judge_ideology['Ideology Score'].apply(lambda x : ~np.isnan(x))]
# Create empty dataframe to be filled by each unique judge-year pair
# A judge-year pair exists if the judge was active in the year
judge_ideo_by_year = pd.DataFrame(columns = ['Name','State','StateCode','Year','Ideology Score'])
# Fill dataframe
for index, row in judge_ideology.iterrows():
name = row['Name']
state = row['State']
statecode = row['StateCode']
app_year = int(row['Year of Appointment'])
# If the judge is still active in 2004, the year of departure is '9999'
dep_year = np.min([2004, int(row['Year of Departure'])])
ideo = row['Ideology Score']
for year in range(app_year, dep_year + 1):
judge_ideo_by_year = judge_ideo_by_year.append({'Name':name,'State':state,'StateCode':statecode,
'Year':year,'Ideology Score':ideo},
ignore_index = True)
# Add absolute ideology score
judge_ideo_by_year['Absolute Ideology Score'] = judge_ideo_by_year['Ideology Score'].apply(np.abs)
# Now group by year and state, and take means
state_ideo_by_year = judge_ideo_by_year.groupby(['Year','State','StateCode']).mean().reset_index()
# Scale ideology score for readability
state_ideo_by_year['Ideology Score'] = state_ideo_by_year['Ideology Score'].apply(lambda x: 100*x)
state_ideo_by_year['Absolute Ideology Score'] = state_ideo_by_year['Absolute Ideology Score'].apply(lambda x: 100*x)
# Here is what a random sample of the data looks like
state_ideo_by_year.sample(10)
Year | State | StateCode | Ideology Score | Absolute Ideology Score | |
---|---|---|---|---|---|
2123 | 1976 | Nevada | NV | -14.399999 | 14.399999 |
1969 | 1973 | Nebraska | NE | 39.649999 | 39.649999 |
3346 | 2000 | Nebraska | NE | 8.387500 | 29.562500 |
2196 | 1977 | Wyoming | WY | 43.399999 | 43.399999 |
3355 | 2000 | Oklahoma | OK | 10.771429 | 24.714286 |
2680 | 1987 | Mississippi | MS | 18.668750 | 18.668750 |
1831 | 1970 | Tennessee | TN | -9.843750 | 26.043751 |
266 | 1918 | Texas | TX | -5.300000 | 5.300000 |
1316 | 1960 | New Jersey | NJ | -12.700000 | 12.785714 |
3033 | 1994 | Maryland | MD | 1.200000 | 28.320000 |
# Make interactive map of average state judge ideology by year
# Create dict of US presidents by year
president_by_year = dict(
[(n, 'George W. Bush')
for n in range(2001, 2005)] +
[(n, 'Bill Clinton')
for n in range(1993, 2001)] +
[(n, 'George H. W. Bush')
for n in range(1989, 1993)] +
[(n, 'Ronald Reagan')
for n in range(1981, 1989)] +
[(n, 'Jimmy Carter')
for n in range(1977, 1981)] +
[(n, 'Gerald Ford')
for n in range(1975, 1977)] +
[(n, 'Richard Nixon')
for n in range(1969, 1975)] +
[(n, 'Lyndon B. Johnson')
for n in range(1964, 1969)] +
[(n, 'John F. Kennedy')
for n in range(1961, 1964)] +
[(n, 'Dwight D. Eisenhower')
for n in range(1956, 1961)]
)
# Choose a colour scale from blue (democrat) to red (republican)
demrep_scl = [
[0.0, 'rgb(0,24,229)'],
[0.2, 'rgb(38,19,186)'],
[0.4, 'rgb(76,14,144)'],
[0.6, 'rgb(114,9,102)'],
[0.8, 'rgb(152,4,60)'],
[1.0, 'rgb(191,0,18)']
]
# Choose a colour scale from light (low) to dark (high)
hl_scl = [
[0.0, 'rgb(247,232,206)'],
[0.2, 'rgb(248,219,171)'],
[0.4, 'rgb(249,207,137)'],
[0.6, 'rgb(250,194,102)'],
[0.8, 'rgb(251,182,68)'],
[1.0, 'rgb(252,170,34)']
]
def plot_ideology_by_year(beginyear = 1956, scl = None, absolute = False):
plotly.offline.init_notebook_mode()
if absolute:
ideo = 'Absolute Ideology Score'
zmin = 0
text = 'Average Absolute Judge Ideology Score by State and Year'
else:
ideo = 'Ideology Score'
zmin = -60
text = 'Average Judge Ideology Score by State and Year'
# Create dict of data to feed into plotly.
data = [dict(type='choropleth',
marker = go.choropleth.Marker(
line = go.choropleth.marker.Line(
color = 'rgb(255,255,255)',
width = 1.5
)),
hoverinfo = 'z+text',
colorbar = go.choropleth.ColorBar(
title = ideo,
thickness = 40
),
colorscale = scl,
zmin = zmin,
zmax = 60,
autocolorscale = False,
locations = state_ideo_by_year[state_ideo_by_year['Year'] == year]['StateCode'],
z = state_ideo_by_year[state_ideo_by_year['Year'] == year][ideo].astype(float),
text = state_ideo_by_year[state_ideo_by_year['Year'] == year]['State'],
locationmode='USA-states')
for year in range(beginyear,2005)]
# Create slider for the map
steps = []
for i in range(len(data)):
step = dict(method='update',
args = [
# Make the ith trace visible
{'visible': [False for t in range(len(data))]},
# Set the title for the ith trace
{'title.text': text + "<br />" + f"President is {president_by_year[i+beginyear]}"}],
label='Year {}'.format(i + beginyear))
step['args'][0]['visible'][i] = True
steps.append(step)
sliders = [dict(active=0,
pad={"t": 1},
steps=steps)]
# Define layout
layout = dict(geo = go.layout.Geo(
scope = 'usa',
projection = go.layout.geo.Projection(type = 'albers usa')),
sliders=sliders,
title = {'text': text + "<br />" + f"President is {president_by_year[i+beginyear]}"}
)
# Create map with plotly
fig = dict(data=data, layout=layout)
return plotly.offline.iplot(fig)
plot_ideology_by_year(scl = demrep_scl, absolute = False)
plot_ideology_by_year(scl = hl_scl, absolute = True)