|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import altair as alt |
|
import pandas as pd |
|
from vega_datasets import data as vega_data |
|
import panel as pn |
|
import datetime as dt |
|
|
|
|
|
df2=pd.read_csv("https://raw.githubusercontent.com/dallascard/SI649_public/main/altair_hw3/approval_topline.csv") |
|
df2['timestamp']=pd.to_datetime(df2['timestamp']) |
|
df2=pd.melt(df2, id_vars=['president', 'subgroup', 'timestamp'], value_vars=['approve','disapprove']).rename(columns={'variable':'choice', 'value':'rate'}) |
|
|
|
|
|
pn.extension(design ='bootstrap') |
|
pn.extension('vega') |
|
|
|
|
|
df2 = df2[df2['choice'] =='approve'] |
|
def create_plot(subgroup, date_range, moving_av_window): |
|
|
|
|
|
filtered = df2[df2['subgroup'] == subgroup] |
|
filtered = filtered[(filtered['timestamp'].dt.date >= date_range[0]) & (filtered['timestamp'].dt.date <= date_range[1])] |
|
filtered['smoothed'] = filtered['rate'].rolling(window=moving_av_window, min_periods=1).mean().shift(-1) |
|
|
|
|
|
line = alt.Chart(filtered).mark_line(color='red').encode( |
|
x=alt.X('timestamp:T'), |
|
y = alt.Y('smoothed').scale(domain=(30, 60)) |
|
) |
|
|
|
|
|
scatter = alt.Chart(filtered).mark_point(filled=True, color='gray', size = 6).encode( |
|
x = alt.X('timestamp:T'), |
|
y = alt.Y('rate').scale(domain=(30, 60)), |
|
) |
|
|
|
|
|
plot = line + scatter |
|
|
|
|
|
return plot |
|
|
|
|
|
|
|
select = pn.widgets.Select(name='Select', options=['All polls','Adults','Voters']) |
|
|
|
|
|
|
|
date_range_slider = pn.widgets.DateRangeSlider( |
|
name='Date Range Slider', |
|
start=dt.datetime(2021, 1, 26).date(), end=dt.datetime(2023, 2, 14).date(), |
|
value=(dt.datetime(2021, 1, 26).date(), dt.datetime(2023, 2, 14).date()), |
|
step=2 |
|
) |
|
|
|
|
|
|
|
win_slider = pn.widgets.IntSlider(name='Moving Average Window', start=1, end=80, step=1, value=20) |
|
|
|
|
|
bplot = pn.bind(create_plot, subgroup=select, |
|
date_range=date_range_slider,moving_av_window = win_slider ) |
|
|
|
|
|
|
|
viz4 = pn.Column(bplot,select,date_range_slider,win_slider) |
|
|
|
viz4.show() |