lab7 / app.py
chw223's picture
Update app.py
e3c43cd verified
# import io
# import random
# from typing import List, Tuple
# from PIL import Image
# from transformers import CLIPModel, CLIPProcessor
# imports we will use
# import warnings
# warnings.simplefilter(action='ignore', category=FutureWarning)
import altair as alt
import pandas as pd
from vega_datasets import data as vega_data
import panel as pn
import datetime as dt
#load data
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'})
# Enable Panel extensions
pn.extension(design ='bootstrap')
pn.extension('vega')
# Define a function to create and return a plot
df2 = df2[df2['choice'] =='approve']
def create_plot(subgroup, date_range, moving_av_window):
# Apply any required transformations to the data in pandas
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 chart
line = alt.Chart(filtered).mark_line(color='red').encode(
x=alt.X('timestamp:T'),
y = alt.Y('smoothed').scale(domain=(30, 60))
)
# Scatter plot with individual polls
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)),
)
# Put them together
plot = line + scatter
# Return the combined chart
return plot
# Create the selection widget
select = pn.widgets.Select(name='Select', options=['All polls','Adults','Voters'])
# Create the slider for the date range
# Reference https://panel.holoviz.org/reference/widgets/DateRangeSlider.html
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
)
# Create the slider for the moving average window
# Reference Int Slider: https://panel.holoviz.org/reference/widgets/IntSlider.html
win_slider = pn.widgets.IntSlider(name='Moving Average Window', start=1, end=80, step=1, value=20)
# Bind the widgets to the create_plot function
bplot = pn.bind(create_plot, subgroup=select,
date_range=date_range_slider,moving_av_window = win_slider )
# Combine everything in a Panel Column to create an app
# Reference: https://panel.holoviz.org/how_to/streamlit_migration/interactivity.html
viz4 = pn.Column(bplot,select,date_range_slider,win_slider)
# set the app to be servable
viz4.show()