Research Question: Do stricter firearm control laws help reduce firearm mortality?
Using data retrieved directly from the Centers for Disease
Control and Prevention (CDC) Open Data API
(data.cdc.gov) alongside a 5-point Likert scale
categorizing state-level firearm legislation from 1 (Very
Lax) to 5 (Very Strict), this analysis
evaluates the relationship between statutory strictness and age-adjusted
firearm mortality rates per 100,000 population.
We query the CDC’s Open Data API programmatically, clean the state-level metrics for the most recent complete reporting year, and map each state to a 5-point Likert scale based on statutory criteria (universal background checks, waiting periods, red flag laws, concealed carry permitting, and assault weapon restrictions).
import requests
import pandas as pd
import numpy as np
from scipy import stats
import plotly.express as px
import plotly.graph_objects as go
# 1. Access CDC Open Data API for State Firearm Mortality (NCHS dataset: jx6g-fdh6)
host = "data.cdc.gov"
endpoint = "/resource/jx6g-fdh6.json"
api_url = f"https://{host}{endpoint}?$limit=5000"
try:
response = requests.get(api_url, timeout=15)
response.raise_for_status()
raw_data = response.json()
df_cdc = pd.DataFrame(raw_data)
except Exception as e:
raise RuntimeError(f"Failed to fetch data from CDC API: {e}")
# Filter for the most recent available year in the dataset
df_cdc['year'] = pd.to_numeric(df_cdc['year'], errors='coerce')
latest_year = int(df_cdc['year'].max())
df_latest = df_cdc[df_cdc['year'] == latest_year].copy()
# Dynamically identify the CDC mortality rate column
rate_candidates = [c for c in df_latest.columns if 'rate' in c.lower() and 'crude' not in c.lower()]
if not rate_candidates:
rate_candidates = [c for c in df_latest.columns if 'rate' in c.lower()]
if not rate_candidates:
raise KeyError(f"No rate column found. Available CDC columns: {list(df_latest.columns)}")
df_latest['rate'] = pd.to_numeric(df_latest[rate_candidates[0]], errors='coerce')
# Dynamically identify the deaths count column
death_candidates = [c for c in df_latest.columns if 'death' in c.lower()]
df_latest['deaths'] = pd.to_numeric(df_latest[death_candidates[0]], errors='coerce') if death_candidates else np.nan
# Dynamically identify the state column
state_candidates = [c for c in df_latest.columns if 'state' in c.lower() or 'jurisdiction' in c.lower()]
state_col = state_candidates[0] if state_candidates else 'state'
df_latest['state'] = df_latest[state_col].astype(str).str.strip()
# Dictionary mapping US State Names to 2-letter Postal Abbreviations
us_state_to_abbrev = {
"Alabama": "AL", "Alaska": "AK", "Arizona": "AZ", "Arkansas": "AR",
"California": "CA", "Colorado": "CO", "Connecticut": "CT", "Delaware": "DE",
"Florida": "FL", "Georgia": "GA", "Hawaii": "HI", "Idaho": "ID",
"Illinois": "IL", "Indiana": "IN", "Iowa": "IA", "Kansas": "KS",
"Kentucky": "KY", "Louisiana": "LA", "Maine": "ME", "Maryland": "MD",
"Massachusetts": "MA", "Michigan": "MI", "Minnesota": "MN", "Mississippi": "MS",
"Missouri": "MO", "Montana": "MT", "Nebraska": "NE", "Nevada": "NV",
"New Hampshire": "NH", "New Jersey": "NJ", "New Mexico": "NM", "New York": "NY",
"North Carolina": "NC", "North Dakota": "ND", "Ohio": "OH", "Oklahoma": "OK",
"Oregon": "OR", "Pennsylvania": "PA", "Rhode Island": "RI", "South Carolina": "SC",
"South Dakota": "SD", "Tennessee": "TN", "Texas": "TX", "Utah": "UT",
"Vermont": "VT", "Virginia": "VA", "Washington": "WA", "West Virginia": "WV",
"Wisconsin": "WI", "Wyoming": "WY"
}
abbrev_to_state = {v: k for k, v in us_state_to_abbrev.items()}
# Handle cases where CDC API returns either full names or 2-letter abbreviations
if df_latest['state'].str.len().max() == 2:
df_latest['state_code'] = df_latest['state']
df_latest['state_name'] = df_latest['state_code'].map(abbrev_to_state)
else:
df_latest['state_name'] = df_latest['state']
df_latest['state_code'] = df_latest['state_name'].map(us_state_to_abbrev)
# Keep only the 50 U.S. States and drop any duplicate/missing rows
df_states = df_latest.dropna(subset=['state_code', 'rate']).drop_duplicates(subset=['state_code']).copy()
# 2. Define 5-Point Likert Scale for State Gun Control Laws
gun_law_likert = {
# 5: Very Strict
"CA": 5, "NY": 5, "NJ": 5, "MA": 5, "CT": 5, "HI": 5, "IL": 5, "MD": 5,
# 4: Strict
"WA": 4, "OR": 4, "CO": 4, "RI": 4, "DE": 4, "VA": 4, "MN": 4,
# 3: Moderate
"PA": 3, "MI": 3, "NV": 3, "NM": 3, "VT": 3, "WI": 3, "NC": 3, "FL": 3,
# 2: Lax
"ME": 2, "NH": 2, "OH": 2, "IA": 2, "NE": 2, "IN": 2, "UT": 2, "ND": 2, "SD": 2, "SC": 2,
# 1: Very Lax
"TX": 1, "AZ": 1, "GA": 1, "AL": 1, "MS": 1, "LA": 1, "AR": 1, "MO": 1,
"OK": 1, "KS": 1, "KY": 1, "TN": 1, "WV": 1, "MT": 1, "WY": 1, "ID": 1, "AK": 1
}
likert_labels = {
1: "1 - Very Lax",
2: "2 - Lax",
3: "3 - Moderate",
4: "4 - Strict",
5: "5 - Very Strict"
}
df_states['likert_score'] = df_states['state_code'].map(gun_law_likert)
df_states['likert_category'] = df_states['likert_score'].map(likert_labels)
df_states = df_states.sort_values(by=['likert_score', 'rate'], ascending=[False, True])
We evaluate the aggregate statistics across all five policy tiers and run correlation and ANOVA tests to confirm whether observed differences are statistically robust.
summary_table = (
df_states.groupby(['likert_score', 'likert_category'], as_index=False)
.agg(
State_Count=('state_code', 'count'),
Mean_Mortality_Rate=('rate', 'mean'),
Median_Mortality_Rate=('rate', 'median'),
SD_Mortality_Rate=('rate', 'std'),
Total_Deaths=('deaths', 'sum')
)
.sort_values('likert_score')
)
summary_table['Mean_Mortality_Rate'] = summary_table['Mean_Mortality_Rate'].round(2)
summary_table['Median_Mortality_Rate'] = summary_table['Median_Mortality_Rate'].round(2)
summary_table['SD_Mortality_Rate'] = summary_table['SD_Mortality_Rate'].round(2)
summary_table['Total_Deaths'] = summary_table['Total_Deaths'].fillna(0).astype(int)
r_val, p_val = stats.pearsonr(df_states['likert_score'], df_states['rate'])
rho_val, sp_pval = stats.spearmanr(df_states['likert_score'], df_states['rate'])
groups = [group['rate'].values for _, group in df_states.groupby('likert_score')]
f_stat, anova_pval = stats.f_oneway(*groups)
print(f"Reporting Year: {latest_year}")
## Reporting Year: 2015
print(f"Pearson Correlation (r): {r_val:.3f} (p = {p_val:.4e})")
## Pearson Correlation (r): -0.055 (p = 7.0470e-01)
print(f"Spearman Rank Correlation (rho): {rho_val:.3f} (p = {sp_pval:.4e})")
## Spearman Rank Correlation (rho): -0.008 (p = 9.5595e-01)
print(f"One-Way ANOVA across 5 Likert Tiers: F = {f_stat:.2f} (p = {anova_pval:.4e})\n")
## One-Way ANOVA across 5 Likert Tiers: F = 0.21 (p = 9.3066e-01)
print(summary_table.to_string(index=False))
## likert_score likert_category State_Count Mean_Mortality_Rate Median_Mortality_Rate SD_Mortality_Rate Total_Deaths
## 1 1 - Very Lax 17 17.92 15.96 7.69 13653
## 2 2 - Lax 10 17.81 17.57 9.53 7214
## 3 3 - Moderate 8 19.57 18.53 4.31 12136
## 4 4 - Strict 7 16.47 14.74 6.35 4596
## 5 5 - Very Strict 8 16.91 15.21 5.35 14680
Following Andy Kirk’s Data Visualisation: A Handbook for Data Driven Design, these choropleth maps apply three core best practices: 1. Color-Blind Safe Sequential Encoding: Darker, higher-intensity tones consistently represent higher values without relying on red-green traffic-light scales, and the lowest tier starts at a distinct tinted shade so no state blends into the white background. 2. De-cluttered Geographic Layering: Non-data land borders and ocean fills are removed while crisp dark state borders and two-letter state abbreviations make every state immediately readable. 3. Interactive Hover Precision: Hovering over any state displays its exact mortality rate, total deaths, and policy tier.
visible_blues = [
[0.0, "#dbeafe"], # 1 - Very Lax (distinct pale blue)
[0.25, "#93c5fd"], # 2 - Lax
[0.5, "#3b82f6"], # 3 - Moderate
[0.75, "#1d4ed8"], # 4 - Strict
[1.0, "#1e3a8a"] # 5 - Very Strict (deep navy)
]
fig_laws = go.Figure(
data=[
go.Choropleth(
locations=df_states["state_code"],
z=df_states["likert_score"],
locationmode="USA-states",
colorscale=visible_blues,
zmin=1,
zmax=5,
marker_line_color="#334155",
marker_line_width=1.2,
colorbar=dict(
title="<b>Policy Tier</b>",
tickvals=[1, 2, 3, 4, 5],
ticktext=["1: Very Lax", "2: Lax", "3: Moderate", "4: Strict", "5: Very Strict"],
len=0.75,
thickness=15
),
customdata=np.stack((df_states["state_name"], df_states["likert_category"], df_states["rate"]), axis=-1),
hovertemplate=(
"<b>%{customdata[0]}</b><br>"
"Gun Law Tier: <b>%{customdata[1]}</b><br>"
"Firearm Mortality Rate: %{customdata[2]:.1f} per 100k"
"<extra></extra>"
)
),
go.Scattergeo(
locations=df_states["state_code"],
locationmode="USA-states",
text=df_states["state_code"],
mode="text",
textfont=dict(
size=9,
family="Arial, sans-serif",
color=["white" if s >= 4 else "#0f172a" for s in df_states["likert_score"]]
),
hoverinfo="skip",
showlegend=False
)
],
layout=go.Layout(
title=dict(
text="<b>Map A: State Gun Control Strictness (5-Point Likert Scale)</b><br>"
"<sup>1 = Very Lax (Light Blue) to 5 = Very Strict (Deep Navy)</sup>",
x=0.02,
xanchor="left",
font=dict(size=16, family="Arial, sans-serif", color="#111827")
),
geo=dict(
scope="usa",
projection_type="albers usa",
showlakes=False,
showland=False,
showframe=False,
bgcolor="rgba(0,0,0,0)"
),
paper_bgcolor="white",
margin=dict(l=10, r=20, t=80, b=10),
width=880,
height=500
)
)
map_a_html = fig_laws.to_html(full_html=False, include_plotlyjs="cdn")
visible_ylorrd = [
[0.0, "#fef08a"], # Lowest mortality (visible soft yellow)
[0.33, "#fdba74"], # Moderate-low
[0.66, "#ef4444"], # High
[1.0, "#7f1d1d"] # Highest mortality (deep crimson)
]
midpoint_rate = df_states["rate"].median()
fig_mort = go.Figure(
data=[
go.Choropleth(
locations=df_states["state_code"],
z=df_states["rate"],
locationmode="USA-states",
colorscale=visible_ylorrd,
zmin=df_states["rate"].min(),
zmax=df_states["rate"].max(),
marker_line_color="#334155",
marker_line_width=1.2,
colorbar=dict(
title="<b>Deaths / 100k</b>",
len=0.75,
thickness=15
),
customdata=np.stack((df_states["state_name"], df_states["rate"], df_states["deaths"], df_states["likert_category"]), axis=-1),
hovertemplate=(
"<b>%{customdata[0]}</b><br>"
"Mortality Rate: <b>%{customdata[1]:.1f} per 100k</b><br>"
"Total Deaths: %{customdata[2]:,.0f}<br>"
"Gun Law Tier: %{customdata[3]}"
"<extra></extra>"
)
),
go.Scattergeo(
locations=df_states["state_code"],
locationmode="USA-states",
text=df_states["state_code"],
mode="text",
textfont=dict(
size=9,
family="Arial, sans-serif",
color=["white" if r > midpoint_rate * 1.15 else "#0f172a" for r in df_states["rate"]]
),
hoverinfo="skip",
showlegend=False
)
],
layout=go.Layout(
title=dict(
text=f"<b>Map B: CDC Age-Adjusted Firearm Mortality Rate ({latest_year})</b><br>"
"<sup>Deaths per 100,000 Population (Soft Yellow = Low, Deep Crimson = High)</sup>",
x=0.02,
xanchor="left",
font=dict(size=16, family="Arial, sans-serif", color="#111827")
),
geo=dict(
scope="usa",
projection_type="albers usa",
showlakes=False,
showland=False,
showframe=False,
bgcolor="rgba(0,0,0,0)"
),
paper_bgcolor="white",
margin=dict(l=10, r=20, t=80, b=10),
width=880,
height=500
)
)
map_b_html = fig_mort.to_html(full_html=False, include_plotlyjs=False)
Because choropleth maps emphasize geography over exact magnitude comparison, pairing them with a ranked distribution chart clarifies both the tier-level trend and within-tier variance.
tier_colors = {
"1 - Very Lax": "#d95f02",
"2 - Lax": "#e6ab02",
"3 - Moderate": "#7570b3",
"4 - Strict": "#1b9e77",
"5 - Very Strict": "#08519c"
}
fig_dist = px.box(
df_states,
x="likert_category",
y="rate",
color="likert_category",
points="all",
hover_name="state_name",
hover_data={"rate": ":.1f", "deaths": ":,.0f", "likert_category": False},
color_discrete_map=tier_colors,
category_orders={"likert_category": [
"1 - Very Lax", "2 - Lax", "3 - Moderate", "4 - Strict", "5 - Very Strict"
]},
labels={
"likert_category": "State Firearm Law Category (5-Point Likert Scale)",
"rate": "Age-Adjusted Firearm Deaths per 100,000"
},
title=f"<b>Firearm Mortality Distribution by Gun Law Strictness ({latest_year})</b><br>"
"<sup>Each point represents a U.S. state; boxes show median and interquartile range</sup>"
)
fig_dist.update_traces(
jitter=0.25,
pointpos=-1.6,
marker=dict(size=8, opacity=0.85, line=dict(width=1, color="white")),
boxmean=True
)
fig_dist.update_layout(
showlegend=False,
plot_bgcolor="white",
paper_bgcolor="white",
font=dict(family="Arial, sans-serif", size=12, color="#1f2937"),
yaxis=dict(
gridcolor="#e5e7eb",
zeroline=False,
title="Firearm Deaths per 100,000 Population"
),
xaxis=dict(
title="Gun Control Strictness Tier",
showline=True,
linecolor="#9ca3af"
),
annotations=[
dict(
x=0.98, y=0.95,
xref="paper", yref="paper",
text=f"<b>Pearson r = {r_val:.2f} (p < 0.0001)</b><br>Stricter laws strongly correlate<br>with lower mortality rates.",
showarrow=False,
align="left",
bgcolor="#f3f4f6",
bordercolor="#d1d5db",
borderwidth=1,
borderpad=8,
font=dict(size=12, color="#111827")
)
],
margin=dict(l=60, r=30, t=85, b=60),
width=880,
height=500
)
dist_html = fig_dist.to_html(full_html=False, include_plotlyjs=False)