import pandas as pd
import plotly.express as px
elec = pd.read_csv("https://raw.githubusercontent.com/alex/nyt-2020-election-scraper/master/battleground-state-changes.csv")
elec.timestamp = pd.to_datetime(elec.timestamp, format="%Y-%m-%d %H:%M:%S.%f").dt.round(freq = "s")
elec["votes_biden"] = 0
elec["votes_trump"] = 0
filter_trump_leads = elec["leading_candidate_name"] == "Trump"
filter_biden_leads = elec["leading_candidate_name"] == "Biden"
# where trump leads
elec.loc[filter_trump_leads, "votes_trump"] = elec.loc[filter_trump_leads, "leading_candidate_votes"]
elec.loc[filter_trump_leads, "votes_biden"] = elec.loc[filter_trump_leads, "trailing_candidate_votes"]
# where biden leads
elec.loc[filter_biden_leads, "votes_trump"] = elec.loc[filter_biden_leads, "trailing_candidate_votes"]
elec.loc[filter_biden_leads, "votes_biden"] = elec.loc[filter_biden_leads, "leading_candidate_votes"]
# remove zeroes
elec = elec.loc[(elec.votes_biden != 0) | (elec.votes_trump != 0), :]
px.line(
elec,
x='timestamp',
y=["votes_biden", "votes_trump"],
facet_col="state",
facet_col_wrap=1,
width=600,
height=600
).update_yaxes(
matches=None
)
states = elec.state.unique()
states
state_rank = 2
px.line(
elec.loc[elec.state == states[state_rank], :],
x='timestamp',
y=["votes_biden", "votes_trump"],
title = states[state_rank]
)