Spaces:
Runtime error
Runtime error
# Import panel and vega datasets | |
import panel as pn | |
import vega_datasets | |
# Enable Panel extensions | |
pn.extension() | |
maincol = pn.Column() | |
# Define a function to create and return a plot | |
df2_approve = df2[df2['choice'] == 'approve'] | |
def create_plot(subgroup, date_range, moving_av_window): | |
# Apply any required transformations to the data in pandas | |
filtered_data = df2_approve[df2_approve['subgroup'] == subgroup] | |
start_date, end_date = pd.to_datetime(date_range[0]), pd.to_datetime(date_range[1]) | |
filtered_data = filtered_data[(filtered_data['timestamp'] >= start_date) & (filtered_data['timestamp'] <= end_date)] | |
filtered_data['rate_change'] = filtered_data['rate'].rolling(window=moving_av_window).mean() | |
# Line chart | |
base_line = alt.Chart(filtered_data).mark_line(color='red', size=2).encode( | |
x='timestamp:T', | |
y=alt.Y('rate_change:Q', scale=alt.Scale(domain=[30, 60])) | |
) | |
# Scatter plot with individual polls | |
base_scatter = alt.Chart(filtered_data).mark_point(size=2, opacity=0.7, color="gray").encode( | |
x='timestamp:T', | |
y=alt.Y('rate:Q'), | |
) | |
# Put them togetehr | |
plot = (base_scatter + base_line) | |
# Return the combined chart | |
return plot | |
# Create the selection widget | |
subgroup_widget = pn.widgets.Select(name="Select", options=['Adults', 'All polls', 'Voters']) | |
# Create the slider for the date range | |
date_slider = pn.widgets.DateRangeSlider( | |
name='Date Range Slider', | |
start = pd.to_datetime('2021-01-26'), | |
end = pd.to_datetime('2023-02-14'), | |
value = (pd.to_datetime('2021-01-26'), pd.to_datetime('2023-02-14')) | |
) | |
# Create the slider for the moving average window | |
window_widget = pn.widgets.IntSlider(name="Moving average window", value=1, start=1, end=100, step=1) | |
# Bind the widgets to the create_plot function | |
bound_plot=pn.bind(create_plot, subgroup=subgroup_widget, date_range=date_slider, moving_av_window=window_widget) | |
# Combine everything in a Panel Column to create an app | |
maincol.append(subgroup_widget) | |
maincol.append(date_slider) | |
maincol.append(window_widget) | |
maincol.append(bound_plot) | |
# set the app to be servable | |
maincol.servable() |