Last active
November 25, 2024 18:01
-
-
Save corintxt/71e691b9a7d5f677e3630a15af46361b to your computer and use it in GitHub Desktop.
Chart styling with matplotlib
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
import matplotlib.pyplot as plt | |
csv = pd.read_csv('https://raw.githubusercontent.com/corintxt/AFP_data/refs/heads/main/data/US_VEP_Turnout_Rates_v1.1.csv') | |
df = csv[['YEAR','TURNOUT_RATE_PRES']] \ | |
.dropna()\ | |
.query('YEAR >= 1900') | |
### DRAW THE CHART | |
# Font settings | |
plt.rcParams.update( | |
{'font.family': 'Source Sans Pro', | |
"svg.fonttype": 'none' | |
}) | |
# Define plot size | |
plt.figure(figsize=(6, 4)) | |
## Plot the data | |
plt.plot(df['YEAR'], | |
df['TURNOUT_RATE_PRES'], | |
linewidth=2) | |
## Set title and subtitle | |
plt.suptitle("US election turnout", | |
x=0.1, | |
y=1.02, | |
fontsize=20, | |
fontweight='bold', | |
ha='left') | |
plt.title("Voter turnout in the 2024 election was still among the highest since 1900", | |
x= -.03, | |
pad=15, | |
fontsize=10, | |
fontweight='semibold', | |
ha='left', | |
) | |
# Add source credit | |
plt.figtext(0.1, 0.01, | |
"Source: UF Election Lab", | |
ha="left", | |
fontsize=8) | |
### FORMAT THE CHART | |
# Remove frame | |
ax = plt.gca() | |
ax.set_frame_on(False) | |
# Control Y start and end point | |
ax.set_ylim([0.44, 0.75]) | |
# Change decimal to percentage | |
ticks = ax.get_yticks() | |
ax.set_yticklabels(['{:,.0%}'.format(x) for x in ticks]) | |
# Define custom grid marks | |
ax.grid(axis="y", | |
color="grey", | |
alpha=.5, | |
linewidth=.5, | |
linestyle="--") | |
# Customize x-ticks | |
plt.tick_params(axis='x', length=5, direction='out') | |
plt.tick_params(axis='y', left=False) | |
# Save svg | |
plt.savefig('election-turnout-afp.svg',bbox_inches='tight') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment