|
import vega_datasets |
|
import panel as pn |
|
import pandas as pd |
|
import altair as alt |
|
from vega_datasets import data |
|
|
|
|
|
pn.extension(design='bootstrap') |
|
|
|
|
|
pn.extension('vega') |
|
|
|
|
|
template = pn.template.BootstrapTemplate( |
|
title='SI649 Lab7 Viz4', |
|
) |
|
|
|
|
|
|
|
|
|
df1 = pd.read_csv( |
|
"https://raw.githubusercontent.com/dallascard/SI649_public/main/altair_hw3/approval_polllist.csv") |
|
df2 = pd.read_csv( |
|
"https://raw.githubusercontent.com/dallascard/SI649_public/main/altair_hw3/approval_topline.csv") |
|
|
|
|
|
pn.extension() |
|
|
|
|
|
|
|
|
|
def create_plot(subgroup, date_range, moving_av_window): |
|
|
|
|
|
|
|
|
|
|
|
df2_filtered = df2[(df2['subgroup'] == subgroup) & (df2['timestamp'] >= pd.Timestamp( |
|
date_range[0])) & (df2['timestamp'] <= pd.Timestamp(date_range[1]))] |
|
|
|
|
|
|
|
df2_filtered['moving_rate'] = df2_filtered['rate'].rolling( |
|
window=moving_av_window).mean().shift(-moving_av_window//2) |
|
|
|
|
|
|
|
line = alt.Chart(df2_filtered).mark_line().encode( |
|
x='timestamp:T', |
|
y='moving_rate:Q', |
|
color=alt.value('red') |
|
).transform_filter( |
|
|
|
alt.FieldOneOfPredicate(field='choice', oneOf=['approve']) |
|
) |
|
|
|
|
|
scatter = alt.Chart(df2_filtered).mark_circle().encode( |
|
x='timestamp:T', |
|
y='rate:Q', |
|
color=alt.value('gray'), |
|
opacity=alt.value(0.7), |
|
tooltip=['timestamp:T', 'rate:Q'], |
|
size=alt.value(10) |
|
).transform_filter( |
|
|
|
alt.FieldOneOfPredicate(field='choice', oneOf=['approve']) |
|
) |
|
|
|
|
|
plot = scatter + line |
|
|
|
|
|
|
|
plot = plot.properties(title="Approval Ratings for Joe Biden") |
|
plot = plot.encode( |
|
y=alt.Y('rate:Q', scale=alt.Scale(domain=[30, 60])) |
|
) |
|
|
|
return plot |
|
|
|
|
|
|
|
selection_subgroup = pn.widgets.Select( |
|
name='Subgroup', options=df2.subgroup.unique().tolist()) |
|
|
|
|
|
|
|
date_range_slider = pn.widgets.DateRangeSlider(name='Date Range', start=df2.timestamp.min( |
|
), end=df2.timestamp.max(), value=(df2.timestamp.min(), df2.timestamp.max())) |
|
|
|
|
|
moving_av_window_slider = pn.widgets.IntSlider( |
|
name='Moving Average Window', start=1, end=30, step=1, value=1) |
|
|
|
create_plot_wgt = pn.bind(create_plot, subgroup=selection_subgroup, |
|
date_range=date_range_slider, moving_av_window=moving_av_window_slider) |
|
|
|
|
|
main_col = pn.Column( |
|
create_plot_wgt, |
|
selection_subgroup, |
|
date_range_slider, |
|
moving_av_window_slider, |
|
) |
|
|
|
main_col.servable() |
|
|