File size: 2,184 Bytes
6e06f17
802ae0c
 
6e06f17
802ae0c
6e06f17
 
 
 
802ae0c
6e06f17
802ae0c
6e06f17
802ae0c
6e06f17
 
 
 
 
 
 
 
 
 
802ae0c
6e06f17
 
 
 
802ae0c
 
6e06f17
 
 
802ae0c
6e06f17
802ae0c
 
6e06f17
 
802ae0c
6e06f17
 
 
 
 
 
802ae0c
 
6e06f17
 
802ae0c
6e06f17
 
802ae0c
6e06f17
 
 
 
 
802ae0c
6e06f17
 
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
# 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()