|
|
|
|
|
import panel as pn |
|
import pandas as pd |
|
import altair as alt |
|
import vega_datasets |
|
|
|
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'}) |
|
df2['timestamp'] = pd.to_datetime(df2['timestamp'], format='%Y-%m').dt.normalize() |
|
|
|
|
|
pn.extension(design='bootstrap') |
|
pn.extension('vega') |
|
|
|
|
|
|
|
def create_plot(subgroup, date_range, moving_av_window): |
|
|
|
|
|
filtered_data = df2[(df2['choice'] == 'approve') & (df2['subgroup'] == subgroup)] |
|
filtered_data = filtered_data[(filtered_data['timestamp'] >= pd.to_datetime(date_range[0])) & (filtered_data['timestamp'] <= pd.to_datetime(date_range[1]))] |
|
filtered_data['smoothed'] = filtered_data['rate'].rolling(window=moving_av_window, min_periods=1).mean() |
|
|
|
|
|
line = alt.Chart(filtered_data).mark_line(color='red', size=2).encode( |
|
x='timestamp:T', |
|
y='smoothed:Q' |
|
) |
|
|
|
|
|
points = alt.Chart(filtered_data).mark_point(color='grey', opacity=0.7, size=2).encode( |
|
x=alt.X('timestamp:T', title=None), |
|
y=alt.Y('rate:Q', scale=alt.Scale(domain=[30, 60]), title='approve,mov_avg') |
|
) |
|
|
|
|
|
plot = points + line |
|
|
|
|
|
return plot |
|
|
|
|
|
|
|
subgroup_select = pn.widgets.Select(name='Select', options=['All polls', 'Adults', 'Voters']) |
|
|
|
|
|
date_range_slider = pn.widgets.DateRangeSlider( |
|
name='Date Range Slider', |
|
start=df2['timestamp'].min(), |
|
end=df2['timestamp'].max(), |
|
value=(df2['timestamp'].min(), df2['timestamp'].max()) |
|
) |
|
|
|
|
|
moving_av_slider = pn.widgets.IntSlider(name='Moving average window', value=34, start=1, end=100) |
|
|
|
|
|
@pn.depends(subgroup_select.param.value, date_range_slider.param.value, moving_av_slider.param.value) |
|
def update_chart(subgroup, date_range, moving_av_window): |
|
return create_plot(subgroup, date_range, moving_av_window) |
|
|
|
|
|
app = pn.Column(update_chart, subgroup_select, date_range_slider, moving_av_slider) |
|
|
|
app.servable() |