File size: 3,754 Bytes
72d7f80
 
 
17efd4c
 
14062f1
 
72d7f80
 
17efd4c
 
72d7f80
 
17efd4c
72d7f80
 
17efd4c
72d7f80
 
 
 
 
 
 
 
 
 
411fe56
 
 
14062f1
 
411fe56
 
eaa6f81
314d76e
411fe56
17efd4c
3136315
17efd4c
 
411fe56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14062f1
411fe56
 
 
 
 
 
 
314d76e
411fe56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3136315
411fe56
 
 
 
 
 
 
3136315
 
411fe56
 
 
 
 
 
 
3136315
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# start with the setup

# supress warnings about future deprecations
# import warnings
# warnings.simplefilter(action='ignore', category=FutureWarning)
import panel as pn
import vega_datasets
import pandas as pd
import altair as alt
# import numpy as np
# import pprint
import datetime as dt
from vega_datasets import data
# import matplotlib.pyplot as plt

# Solve a javascript error by explicitly setting the renderer
# alt.renderers.enable('jupyterlab')

#load data 
# df1=pd.read_csv("https://raw.githubusercontent.com/dallascard/SI649_public/main/altair_hw3/approval_polllist.csv")
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'})



## Viz 4
# Import panel and vega datasets

# import panel as pn
# import vega_datasets

# Enable Panel extensions
pn.extension(design='bootstrap')
pn.extension('vega')

template = pn.template.BootstrapTemplate(
    title='SI649 Altair Assignment 3 (ritaycw)',
)

# 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
    approve_data = df2[df2['choice']=='approve']
    filtered_data = approve_data[approve_data['subgroup'] == subgroup]
    filtered_data = filtered_data[(filtered_data['timestamp'].dt.date >= date_range[0]) & \
                                  (filtered_data['timestamp'].dt.date <= date_range[1])]
    filtered_data['mov_avg'] = filtered_data['rate'].rolling(window=moving_av_window).mean().shift(-moving_av_window//2)

    # Line chart
    smoothed_line = alt.Chart(filtered_data).mark_line(color='red', size=2).encode(
        x='timestamp:T',
        y='mov_avg:Q'
    )

    # Scatter plot with individual polls
    scatter4 = alt.Chart(filtered_data).mark_point(size=2, opacity=0.7, color='grey').encode(
        x='timestamp:T',
        y=alt.Y('rate:Q', title='approve', scale=alt.Scale(domain=[30, 60])),
    )

    # Put them togetehr
    plot = (scatter4+smoothed_line).encode(
        y=alt.Y(axis=alt.Axis(title='approve, mov_avg'))
        )

    # Return the combined chart
    return pn.pane.Vega(plot)

# Create the selection widget
dropdown = pn.widgets.Select(options=['All polls', 'Adults', 'Voters'], name='Select')

# Create the slider for the date range
date_range_slider = pn.widgets.DateRangeSlider(name='Date Range Slider', 
                                               start=df2['timestamp'].dt.date.min(), 
                                               end=df2['timestamp'].dt.date.max(),
                                               value=(df2['timestamp'].dt.date.min(), df2['timestamp'].dt.date.max()),
                                               step=1)

# Create the slider for the moving average window
window_size_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=dropdown, 
                            date_range=date_range_slider, 
                            moving_av_window=window_size_slider))

# window_size_slider

# Combine everything in a Panel Column to create an app
maincol = pn.Column()
maincol.append("# Visualization 4: Interactive smoothing (hosted on Huggingface using Panel)")
maincol.append(final)
maincol.append(dropdown)
maincol.append(date_range_slider)
maincol.append(window_size_slider)


# set the app to be servable
template.main.append(maincol)
template.servable(title="SI649 Altair Assignment 3 (ritaycw)")