File size: 2,518 Bytes
5653dda 762c48d 5653dda afbc655 5653dda cf58608 5653dda 06990e4 22eeff0 5653dda 22eeff0 cf58608 5653dda cf58608 5653dda cf58608 5653dda cf58608 5653dda afbc655 5653dda cf58608 5653dda 22eeff0 5653dda cf58608 22eeff0 5653dda 06990e4 5653dda afbc655 06990e4 5653dda cb5724e 5653dda cb5724e 22eeff0 5653dda |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# Import panel and vega datasets
import panel as pn
import vega_datasets
df2=pd.read_csv("https://raw.githubusercontent.com/dallascard/SI649_public/main/altair_hw3/approval_topline.csv")
df2_approve = df2[df2['choice'] == 'approve']
# Enable Panel extensions
pn.extension()
# pn.extension('vega', 'tabulator')
# pn.extension(design='bootstrap')
# pn.extension('vega')
template = pn.template.BootstrapTemplate(
title='SI649 Altair3',
)
# 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_df = df2_approve[df2_approve['subgroup'] == subgroup]
filtered_df = filtered_df[(filtered_df['timestamp'].dt.date >= date_range[0]) & (filtered_df['timestamp'].dt.date <= date_range[1])]
filtered_df['mov_avg'] = filtered_df['rate'].rolling(window=moving_av_window).mean().shift(moving_av_window//2)
# Line chart
line_chart = alt.Chart(filtered_df).mark_line(color='red', size=2).encode(
x='timestamp:T',
y='mov_avg:Q'
)
# Scatter plot with individual polls
scatter_plot = alt.Chart(filtered_df).mark_point(color='grey', size=2, opacity=0.7).encode(
x='timestamp:T',
y='rate:Q'
)
# Put them togetehr
plot = scatter_plot + line_chart
# 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
date_range_slider = pn.widgets.DateRangeSlider(
name='Date Range Slider',
start=df2_approve['timestamp'].dt.date.min(), end=df2_approve['timestamp'].dt.date.max(),
value=(df2_approve['timestamp'].dt.date.min(), df2_approve['timestamp'].dt.date.max()),
step=1
)
# # Create the slider for the moving average window
moving_av_slider = pn.widgets.IntSlider(name='Moving Average Window', start=1, end=100, value=1)
# Bind the widgets to the create_plot function
final = pn.Row(pn.bind(create_plot,
subgroup=select,
date_range=date_range_slider,
moving_av_window=moving_av_slider))
# # Combine everything in a Panel Column to create an app
maincol=pn.Column()
maincol.append(final)
maincol.append(select)
maincol.append(date_range_slider)
maincol.append(moving_av_slider)
template.main.append(maincol)
# # set the app to be servable
template.serverable(title='SI649 Altair3') |