SI649 / app.py
Neruoy's picture
Update app.py
a8d6ca2 verified
# Import panel and vega datasets
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")
# fix the time stamps and reorganize the data to combine approve and disapprove into one column
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()
# Enable Panel extensions
pn.extension(design='bootstrap')
pn.extension('vega')
# Define a function to create and return a plot
def create_plot(subgroup, date_range, moving_av_window):
# Apply any required transformations to the data in pandas
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 chart
line = alt.Chart(filtered_data).mark_line(color='red', size=2).encode(
x='timestamp:T',
y='smoothed:Q'
)
# Scatter plot with individual polls
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')
)
# Put them togetehr
plot = points + line
# Return the combined chart
return plot
# Create the selection widget
subgroup_select = pn.widgets.Select(name='Select', options=['All polls', 'Adults', 'Voters'])
# Create the slider for the date range
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())
)
# Create the slider for the moving average window
moving_av_slider = pn.widgets.IntSlider(name='Moving average window', value=34, start=1, end=100)
# Bind the widgets to the create_plot function
@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)
# Combine everything in a Panel Column to create an app
app = pn.Column(update_chart, subgroup_select, date_range_slider, moving_av_slider)
app.servable()