Post

Plotly Friday Figure - Week 33

Plotly Friday Figure - Week 33

US Elections

As we approach the next US elections, we thought it would be interesting to view the results of previous elections (from 1976-2020).

Things to consider:

how can the map be improved? It’s hard to distinguish colors between states where vote count is very low.

can we use a different map or graph to tell a data story around historical US elections?

is there a better way to show how each state’s votes differ over time?

would it be advantageous to use polars instead of pandas?

what graph can we use to analyze non-democrat and non-republican party participation (LIBERTARIAN & OTHER)?

Code

```python import plotly.express as px import pandas as pd

df = pd.read_csv(‘https://raw.githubusercontent.com/plotly/Figure-Friday/main/2024/week-33/1976-2020-president.csv’)

Group by year and state, then calculate the vote difference between DEMOCRAT and REPUBLICAN

filtered_data = df[df[‘party_simplified’].isin([‘DEMOCRAT’, ‘REPUBLICAN’])]

Pivot the data to get the vote difference

pivot_data = filtered_data.pivot_table(index=[‘year’, ‘state’], columns=’party_simplified’, values=’candidatevotes’)

Calculate the vote difference between DEMOCRAT and REPUBLICAN

pivot_data[‘vote_diff’] = pivot_data[‘DEMOCRAT’] - pivot_data[‘REPUBLICAN’]

Convert the pivot table back to a regular dataframe

regular_df = pivot_data.reset_index() regular_df.columns = [‘year’, ‘state’, ‘DEMOCRAT’, ‘REPUBLICAN’, ‘vote_diff’]

Merge the abbreviated state column into the regular_df

final_df = regular_df.merge(df[[‘state’, ‘state_po’]], on=’state’, how=’right’)

Create the map

fig = px.choropleth(final_df, geojson=”https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json”, locationmode=’USA-states’, locations=’state_po’, color=’vote_diff’, scope=”usa”, color_continuous_scale=px.colors.diverging.RdBu, color_continuous_midpoint=0, range_color=[-500000,500000], animation_frame=’year’ ) fig.update_layout(margin={“r”:0, “t”:0, “l”:0, “b”:0}) fig.show()

This post is licensed under CC BY 4.0 by the author.