Py.Cafe

kieiks/

wsl-interactive-visualization

Women's Super League Interactive Visualization

DocsPricing
  • app.py
  • ewf_matches.csv
  • ewf_standings.csv
  • requirements.txt
app.py
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
# Import packages
from dash import Dash, html, dcc, callback, Output, Input, State
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import dash_bootstrap_components as dbc

def generate_list(number1_percentage, number2_percentage, total_size=10000):
    number1_count = int(total_size * (number1_percentage))
    number2_count = int(total_size * (number2_percentage))
    number0_count = total_size - number1_count - number2_count
    
    return [2] * number1_count + [1] * number2_count + [0] * number0_count

def win_loss_chart(win,draw):
    # Sample list of 100 numbers
    numbers = generate_list(win,draw)

    # Create a 10x10 array initialized with zeros
    array = np.zeros((100, 100), dtype=int)

    # Fill the array in diagonal order
    k = 0
    for i in range(100):
        for j in range(i + 1):
            if k < 10000:
                array[i - j, j] = numbers[k]
                k += 1

    for i in range(1, 100):
        for j in range(100 - i):
            if k < 10000:
                array[99 - j, i + j] = numbers[k]
                k += 1

    color_scale = [[0,"#d90429"],[0.5,"#edf2f4"],[1,"#2b2d42"]]


    fig = go.Figure()

    fig.add_trace(go.Heatmap(
        z=array[::-1],
        colorscale=color_scale
    ))

    fig.update_xaxes(showticklabels=False,linewidth=1, linecolor='black', mirror=True, showline=True)
    fig.update_yaxes(showticklabels=False,linewidth=1, linecolor='black', mirror=True, showline=True)
    fig.update_layout(width=250,height=250,margin=dict(l=5, r=5, b=5, t=5))
    fig.update_traces(showscale=False)

    return fig

df = pd.read_csv('ewf_standings.csv')
df_seasons = df.groupby('team_name')[['played','wins','draws','losses']].sum()
df_seasons['wins_percentage'] = df_seasons['wins'] / df_seasons['played']
df_seasons['draws_percentage'] = df_seasons['draws'] / df_seasons['played']

df_matches = pd.read_csv('ewf_matches.csv')

def games_played(df, team):

    df_filtered = df[df['match_name'].str.contains(team)]
    df_filtered['Goals Scored'] = np.where(df_filtered['home_team_name'] == "Arsenal Ladies", df_filtered['home_team_score'], df_filtered['away_team_score'])
    df_filtered['Goals Taken'] = np.where(df_filtered['home_team_name'] == "Arsenal Ladies", df_filtered['away_team_score'], df_filtered['home_team_score'])
    df_filtered['Result'] = np.where(df_filtered['Goals Scored'] > df_filtered['Goals Taken'], 1, np.where(df_filtered['Goals Scored'] < df_filtered['Goals Taken'], -1, 0))

    fig = go.Figure()

    fig.add_trace(go.Bar(
        x=df_filtered['date'],
        y=df_filtered['Goals Scored'],
        marker_color=['#2b2d42' if value == 1 else '#8d99ae' for value in df_filtered['Result']]
    ))

    fig.add_trace(go.Bar(
        x=df_filtered['date'],
        y=df_filtered['Goals Taken']*-1,
        marker_color=['#8d99ae' if value == 1 else '#d90429' for value in df_filtered['Result']]
    ))

    fig.add_trace(go.Scatter(
        x=df_filtered['date'],
        y=[df_filtered['Goals Scored'].max() + 2]*len(df_filtered),
        mode='markers',
        marker_size=7,
        marker_symbol='square',
        marker_color = ['#2b2d42' if value == 1 else '#d90429' if value == -1  else '#8d99ae' for value in df_filtered['Result']]
    ))

    fig.update_xaxes(type='category')
    fig.update_yaxes(showticklabels=False)
    fig.update_layout(barmode='relative',showlegend=False,plot_bgcolor='white',margin=dict(l=5, r=5, b=5, t=5))

    fig.add_annotation(
        x=df_filtered['date'].iloc[2],
        y=df_filtered['Goals Scored'].max() + 3,
        text="Win-Loss Ratio",
        showarrow=False,
        xref="x",
        yref="y",
    )

    fig.add_annotation(
        x=df_filtered['date'].iloc[2],
        y=df_filtered['Goals Scored'].max() - 1,
        text="Goals Scored",
        showarrow=False,
        xref="x",
        yref="y",
    )

    fig.add_annotation(
        x=df_filtered['date'].iloc[2],
        y=df_filtered['Goals Taken'].max()*-1,
        text="Goals Taken",
        showarrow=False,
        xref="x",
        yref="y",
    )

    return fig

# Initialize the app
app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
server = app.server

# App layout
app.layout = dbc.Container([
    dbc.Row([
        dbc.Col(html.Div(children='Figure Friday W29', className='text-center h2')),
    ]),
    html.Hr(),
    dbc.Row([
        dbc.Col([
            dcc.Dropdown(id='select_team',options=[{'label':i,'value':i} for i in df_seasons.index.unique()],value=df_seasons.first_valid_index(),multi=False,style={'width': '100%'}),
        ],width=3),
    ]),
    html.Hr(),
    dbc.Row([
        dbc.Col([
            dbc.Row([
                html.B(children='TOTAL STANDINGS',style={'font-size':'40px'}),
                html.Div(id='time',children=''),
                ]),
            html.Br(),
            dbc.Row([
                dbc.Col(html.Div(id='win-loss-text',children='',style={'font-size':'25px'}),width=4,align='center'),
                dbc.Col(dcc.Graph(id='win-loss-chart',figure={}),width=8)
            ])
        ],width=3),
        dbc.Col([
            dbc.Row([
                html.B(children='GAMES PLAYED ALL SEASONS',style={'font-size':'32px'}),
            ]),
            html.Hr(),
            dbc.Row([
                dcc.Graph(id='games-played',figure={})
            ]),
        ])
            
        ])
], fluid=True)

@app.callback(
    Output('time', 'children'),
    Output('win-loss-text', 'children'),
    Output('win-loss-chart', 'figure'),
    Output('games-played', 'figure'),
    Input('select_team', 'value')
    )
def display_click_data(select_team):

    stats = df_seasons.loc[[select_team]]
    win_percentage = stats['wins'] / ( stats['wins'] + stats['draws'] + stats['losses'] )
    draw_percentage = stats['draws'] / ( stats['wins'] + stats['draws'] + stats['losses'] )

    team_name = html.B(stats.index[0].upper(),style={'font-size':'30px'})

    win_loss_text = [
        html.Div(children=f'Wins | {stats["wins"][0]}'),
        html.Br(),
        html.Div(children=f'Draws  | {stats["draws"][0]}'),
        html.Br(),
        html.Div(children=f'Losses | {stats["losses"][0]}'),
    ]

    fig_wlc = win_loss_chart(win_percentage,draw_percentage)

    fig_games = games_played(df_matches,select_team)

    return team_name, win_loss_text, fig_wlc, fig_games
    

# Run the app
if __name__ == '__main__':
    app.run_server(debug=True)