File size: 12,957 Bytes
5e55a06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
########## LIBRARIES ##########
import streamlit as st
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from streamlit_searchbox import st_searchbox
from module.__selectpage__ import st_page_selectbox

########## DATASET ##########
df = pd.read_csv('./data/join_02.csv')
df['date'] = pd.to_datetime(df['date'])                 # Format preparation
df['release_date'] = pd.to_datetime(df['release_date'])
df['avg_peak_perc'] = df['avg_peak_perc'].str.rstrip('%').astype('float') 
df = df.dropna()


########## FUNCTION ##########
##### Adding single-player feature
def add_opp_features(genre):
    df[genre[0]] = (df[genre[1]]==0)*1

##### Adding feature depending on range of a base feature
"""Scenario of using this function
For example, if we want a feature of price
between $10 to $30
"""
def add_range_features(arg):
    lower = arg[0]; upper = arg[1]
    name = arg[2]; genre = arg[3]
    
    condition = (df[genre]>=lower) & (df[genre]<upper)
    df[name] = condition*1

# Returning title version of feature name
def name(target):
    return target.replace('_', ' ').title()

##### Searchbox Functions
# Appending favorite game selected by user to filtered list
    """use after search box
    """
def add_top_games(top_games, favorite_game, ranges, df_ax):
    if favorite_game in top_games: 
        top_games = df_ax.gamename.unique()[ranges[0]-1:ranges[1]+1]
    elif favorite_game!=None: 
        top_games = np.append(top_games, favorite_game)
    return top_games

# Linear search over all gamenames
def search(target):
    gamenames = df['gamename'].unique()                 # all unique gamenames
    result = []
    for gamename in gamenames:
        if target.lower() in gamename.lower():          # games that contains the searching keyword
            result.append(gamename)
    return result 

# Streamlit search box
def searchbox():
    selected_game = st_searchbox(
        search_function=search,
        key="gamename_searchbox",
        default_options=None, 
        placeholder="Compare with your Favorite Game...",
    )
    return selected_game


########## PAGE SECTION ##########
# Datafram Section
    """Dataframe
    together with Title
    """
def dfbox(ax_name, y_name, df_ax):
    title = f"1.1 Dataset of :blue[{ax_name}] Games Sorted by :blue[{y_name}]:"
    st.subheader(title)
    st.dataframe(df_ax)

# plot 1 Section
    """Plot contains the top ranked games
    based on the selected features, 
    within selected genre
    """
def plot1_box(ax, y, order_name, ranges, df_ax, top_games):
    ax_name = name(ax)          # formating strings
    y_name = name(y)            # formeting strings
    
    title = f"1.3 Rank {ranges[0]} to {ranges[1]} :blue[{ax_name}] Games with the :red[{order_name}] :blue[{y_name}]"
    st.subheader(title)

    # Plot 1 - select box
    favorite_game = searchbox()                                                     # search box to add a user favorite game on Plot 1
    top_games = add_top_games(top_games, favorite_game, ranges, df_ax)        
    options = top_games
    selected_options = st.multiselect('Select Video Games', options)

    # Plot 1
    title_names = ','.join(selected_options)
    plot_title = f"Monthly {y_name} of {title_names} Over Time"
    gb = df.sort_values(by='date')
    gb_list = {game: gb[gb["gamename"] == game] for game in selected_options}

    fig_1 = go.Figure()
    fig_1.update_layout(
        title = plot_title, 
        xaxis_title = 'Date',
        yaxis_title = y_name,
    )
    for game, gb in gb_list.items():
        fig_1 = fig_1.add_trace(go.Scatter(x=gb["date"], y=gb[y], name=game, mode='lines'))
    st.plotly_chart(fig_1)

def plot2_box(theme, y, genres, df_bx):
    y_name = name(y)
    
    title = f"2.0 Comparison Among :blue[{theme}] on Monthly :blue[{y_name}]:"
    st.subheader(title)

    # Plot 2 - Multiselect box
    options = genres
    selected_options = st.multiselect('Select Comparing Categories', options)
    selected_names = ','.join(selected_options)                         # formating titles
    plot_title = f"Monthly {y_name} of {selected_names} Over Time"


    # Plot 2

    # Tab 1 - Mean Line Plot
    gb = df_bx.sort_values(by='date')      # New copy of df
    mean_list = {genre: gb[gb[genre] == 1].groupby('date').mean(y).reset_index() for genre in selected_options}

    fig_mean = go.Figure()
    for genre, gb in mean_list.items():
        fig_mean = fig_mean.add_trace(go.Scatter(x=gb['date'], y=gb[y], name=genre, mode='lines'))
    fig_mean.update_layout(
        title = 'Mean of ' + plot_title,
        xaxis_title = 'Date',
        yaxis_title = 'Mean of '+y_name,
    )


    # Tab 2 - Sum Line Plot
    gb = df_bx.sort_values(by='date')
    sum_list = {genre: gb[gb[genre] == 1].groupby('date').sum(y).reset_index() for genre in selected_options}

    fig_sum = go.Figure()
    for genre, gb in sum_list.items():
        fig_sum = fig_sum.add_trace(go.Scatter(x=gb['date'], y=gb[y], name=genre))
    fig_sum.update_layout(
        title = 'Sum of ' + plot_title,
        xaxis_title='Date',
        yaxis_title='Sum of '+y_name,
    )

    # Tab 3 - Scatter / Marker Plot
    gb = df_bx.sort_values(by='date')
    gb_list = {genre: gb[gb[genre] == 1] for genre in selected_options}

    fig_sc = go.Figure()
    for genre, gb in gb_list.items():
        fig_sc = fig_sc.add_trace(go.Scatter(x=gb["date"], y=gb[y], name=genre, mode='markers'))
    fig_sc.update_traces(
        marker=dict(size=4, opacity=0.5)
    )
    fig_sc.update_layout(
        title = plot_title,
        xaxis_title='Date',
        yaxis_title=y_name,
    )


    # Showing Plot
    tab1, tab2, tab3 = st.tabs(['Line Plot', 'Sum Plot', 'Scatter Plot'])
    with tab1:
        st.plotly_chart(fig_mean)
    with tab2:
        st.plotly_chart(fig_sum)
    with tab3:
        st.plotly_chart(fig_sc)


##### Execute Page #####
def exec_page(emoji, theme, page_genres):
    # Select Page
    st_page_selectbox(theme)
    
    # Header
    st.header(emoji)
    st.title(f"Customized Plot on :blue[{theme}]")

    ##### FILTER #####
    # Featuer for both axis
    features = ['avg', 'gain', 'peak', 'avg_peak_perc']
    features += ['metacritic_score', 'positive', 'negative']
    genres = page_genres
    ##################


    # User Menu
    order = st.toggle(label='Rank the Worst Games', value=False)                    # descending order toggle switch
    left_col, right_col = st.columns(2)                                             # Columns dividing 
    with left_col: y = st.selectbox("Select a Feature (y-axis)", features)          # feature select box (y axis of Plots)
    with right_col: ax = st.selectbox("Select a Genre (legend)", genres)            # category select box (filtering game basse on genre)

    order_name='Worst' if order else 'Highest'                                      # string formating
    y_name = name(y)                                            # string of names that would be used on Plot title
    ax_name = name(ax)

    # Data - sorting and filtering
    df_ax = df[df[ax]==1]
    df_ax = df_ax[['gamename', 'date', y, ax]].sort_values(by=y, ascending=order).reset_index()     # Data for Plot 1
    df_bx = df[['gamename', 'date', y]+genres].sort_values(by=y, ascending=order).reset_index()     # Data for Plot 2


    # Slider
    max = df_ax.gamename.unique().tolist()                          # max number of games
    max = len(max)-1
    ranges = st.slider(
        label=f'Select range of the {order_name.lower()} games',
        value = (1, 5), 
        min_value=1, max_value=30, 
        # min_value=1, max_value=max, 
    )
    top_games = df_ax.gamename.unique()[ranges[0]-1:ranges[1]]
    

    # Dataframe preview
    dfbox(ax_name, y_name, df_ax)

    ##### PLOT 1 #####
    # Plot 1 - markdown
    st.markdown("""***""")
    plot1_box(ax, y, order_name, ranges, df_ax, top_games)

    ##### PLOT 2 #####
    # Plot 2 - markdown
    st.markdown("""***""")
    plot2_box(theme, y, genres, df_bx)

##### HOME PAGE #####
def exec_page_home(theme):
    st_page_selectbox(theme)
    
    # Header
    st.header(f"👋 ForcaSteam")
    st.title("Customized Plot on :blue[General Features]")

    ##### FILTER #####
    # Featuer for both axis
    features = ['avg', 'gain', 'peak', 'avg_peak_perc']
    genres = features


    left_col, right_col = st.columns(2)
    order = st.toggle(label='Rank the Worst Games', value=False)        # descending order toggle switch
    y = st.selectbox("Select a Feature (y-axis)", features)                      # feature select box
    order_name='Worst' if order else 'Highest'                          # string formating
    y_name = name(y)

    # Data - sorting and filtering
    df_ax = df[['gamename', 'date', y]].sort_values(by=y, ascending=order).reset_index()    # Data - Plot 1
    # df_bx = df[['gamename', 'date']+features].sort_values(by=y, ascending=order).reset_index()      # Data - Plot 2

    # Slider
    max = df_ax.gamename.unique().tolist()
    max = len(max)-1
    ranges = st.slider(
        label=f'Select range of the {order_name.lower()} games',
        value = (1, 5),
        min_value=1, max_value=30, 
        # min_value=1, max_value=max, 
    )
    top_games = df_ax.gamename.unique()[ranges[0]-1:ranges[1]]

    # Dataframe preview
    dfbox("", y_name, df_ax)


    ##### PLOT 1 #####
    # Plot 1 - markdown
    st.markdown("""***""")
    title = f"1.3 Rank {ranges[0]} to {ranges[1]} Games with the Overall :red[{order_name}] :blue[{y_name}]"
    st.subheader(title)


    # Plot 1 - select box
    favorite_game = searchbox()                                                     # search box to add a user favorite game on Plot 1
    top_games = add_top_games(top_games, favorite_game, ranges, df_ax) 
    options = top_games
    selected_options = st.multiselect('Select Video Games', options)

    # Plot 1
    title_names = ','.join(selected_options)
    plot_title = f"Monthly {y_name} of {title_names} Over Time"
    gb = df_ax.sort_values(by='date')
    gb_list = {game: gb[gb["gamename"] == game] for game in selected_options}

    fig_1 = go.Figure()
    fig_1.update_layout(
        title = plot_title, 
        xaxis_title = 'Date',
        yaxis_title = y_name,
    )
    for game, gb in gb_list.items():
        fig_1 = fig_1.add_trace(go.Scatter(x=gb["date"], y=gb[y], name=game, mode='lines'))
    st.plotly_chart(fig_1)

##### PUBLISHERS PAGE #####
def exec_page_pub(emoji, theme, main_genre):
    st_page_selectbox(theme)
    
    # Header
    st.header(emoji)
    st.title(f"Customized Plot on :blue[{theme}]")

    ##### FILTER #####
    # Featuer for both axis
    features = ['avg', 'gain', 'peak', 'avg_peak_perc']
    features += ['metacritic_score', 'positive', 'negative']
    genres = []

    left_col, right_col = st.columns(2)
    order = st.toggle(label='Find the Worst Games', value=False)        # descending order toggle switch
    with left_col: 
        y = st.selectbox("Select a Feature", features)                  # feature select box
    with right_col: 
        if (main_genre=='publishers'):
            genres = df.sort_values(by=y, ascending=order).publishers.unique()[0:5].tolist()
        elif (main_genre=='developers'):
            genres = df.sort_values(by=y, ascending=order).developers.unique()[0:5].tolist()
        
        for genre in genres:
            df[genre] = (df[main_genre]==genre)*1
        ax = st.selectbox("Select a Category", genres)                  # category select box
    order_name='Worst' if order else 'Highest'                          # string formating
    y_name = y.replace('_', ' ').title()
    ax_name = ax.title().replace('_', ' ')

    # ### adding best publisher features feature ###

    # Data - sorting and filtering
    df_ax = df[df[ax]==1]
    df_ax = df_ax[['gamename', 'date', y, ax]].sort_values(by=y, ascending=order).reset_index()    # Data - Plot 1
    df_bx = df[['gamename', 'date', y]+genres].sort_values(by=y, ascending=order).reset_index()      # Data - Plot 2

    # Slider
    max = df_ax.gamename.unique().tolist()
    max = len(max)
    if(max < 2):value_r = 0
    elif(max > 4):value_r = 5
    else: value_r = max

    ranges = st.slider(
        label=f'Select range of the {order_name.lower()} games',
        value = (1, value_r),
        # min_value=0, max_value=30, 
        min_value=1, max_value=max, 
    )
    top_games = df_ax.gamename.unique()[ranges[0]-1:ranges[1]]

    # Dataframe preview
    dfbox(ax_name, y_name, df_ax)

    title = f"1.2 {ranges[1]} :blue[{ax_name}] Games with the :red[{order_name}] Monthly :blue[{y_name}]:"
    st.subheader(title)
    st.write(top_games)



    ##### PLOT 1 #####
    # Plot 1 - markdown
    st.markdown("""***""")
    plot1_box(ax, y, order_name, ranges, df_ax, top_games)


    ##### PLOT 2 #####
    # Plot 2 - markdown
    st.markdown("""***""")
    plot2_box(theme, y, genres, df_bx)