Py.Cafe

Feanor1992/

CPI Dashboard

Dash Example Explorer

DocsPricing
  • CPI-historical.csv
  • CPI2024.csv
  • app.py
  • 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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from dash import Dash, html, dcc, dash_table
import dash_bootstrap_components as dbc
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.decomposition import PCA
from sklearn.impute import SimpleImputer
from sklearn.feature_selection import SelectKBest, f_classif

cpi_current = pd.read_csv('CPI2024.csv')
cpi_historical = pd.read_csv('CPI-historical.csv')

# Average trend over time
def get_average_historical_figure():
    df_avg = cpi_historical.groupby('Year')['CPI score'].mean().reset_index()
    fig = px.line(
        df_avg,
        x='Year',
        y='CPI score',
        markers=True,
        title='Average Global CPI Score Over Time'
    )
    fig.update_traces(line=dict(color='lightgreen', width=3))
    fig.update_layout(template='plotly_dark')
    return fig

# Historical insights text block
def get_historical_insights_block():
    cpi_delta = (
        cpi_historical.sort_values('Year')
        .groupby('Country / Territory')
        .agg(start_score=('CPI score', lambda x: x.iloc[0]), end_score=('CPI score', lambda x: x.iloc[-1]))
        .assign(change=lambda df: df['end_score'] - df['start_score'])
        .reset_index()
    )
    top_improved = cpi_delta.nlargest(5, 'change')
    top_declined = cpi_delta.nsmallest(5, 'change')
    avg_change = round(cpi_delta['change'].mean(), 2)

    return html.Div([
        html.H4('Historical Trends Insights', style={'color': 'white'}),
        html.P(f"Average global CPI score changed by {avg_change} points since earliest records.", style={'color': 'lightgray'}),
        html.P(f"Top improving countries: {', '.join(top_improved['Country / Territory'])}", style={'color': 'lightgreen'}),
        html.P(f"Top declining countries: {', '.join(top_declined['Country / Territory'])}", style={'color': 'salmon'}),
    ], style={'padding': '1rem', 'backgroundColor': '#111'})

# Insight text from CPI 2024
def get_insights(data):
    avg_score = round(data['CPI 2024 score'].mean(), 2)
    best_country = data.loc[data['CPI 2024 score'].idxmax(), 'Country / Territory']
    worst_country = data.loc[data['CPI 2024 score'].idxmin(), 'Country / Territory']
    return (f"Average CPI Score: {avg_score}. Best ranked country: {best_country}. "
            f"Lowest score: {worst_country}. High CPI correlates with better rank.")

# Processing for Dashboard (CPI2024)
df = cpi_current.copy()
num_cols = df.select_dtypes(include=np.number).columns
cat_cols = df.select_dtypes(include='object').columns

imputer = SimpleImputer(strategy='mean')
df[num_cols] = imputer.fit_transform(df[num_cols])

scaler = StandardScaler()
df[num_cols] = scaler.fit_transform(df[num_cols])

#le = LabelEncoder()
#for col in cat_cols:
#    df[col] = le.fit_transform(df[col].astype(str))

df['Corruption_Level'] = pd.qcut(df['CPI 2024 score'], q=4, labels=['High', 'Moderate', 'Low', 'Very Low'])
le_corr = LabelEncoder()
y = le_corr.fit_transform(df['Corruption_Level'])

pca = PCA(n_components=2)
X_pca = pca.fit_transform(df[num_cols])
df['PCA1'], df['PCA2'] = X_pca[:, 0], X_pca[:, 1]

selector = SelectKBest(score_func=f_classif, k=5)
X_selected = selector.fit_transform(df[num_cols], y)
important_features = df[num_cols].columns[selector.get_support()].tolist()

# Figures
fig_dist = px.histogram(
    cpi_current,
    x='CPI 2024 score',
    nbins=30,
    title='Distribution of CPI Scores'
)
fig_dist.update_layout(template='plotly_dark')

fig_scatter = px.scatter(
    cpi_current,
    x='Rank',
    y='CPI 2024 score',
    color='Region',
    title='CPI Score vs Rank by Region',
    hover_name='Country / Territory'
)
fig_scatter.update_layout(template='plotly_dark')

cpi_average = cpi_current['CPI 2024 score'].mean()
fig_choropleth = px.choropleth(
    cpi_current,
    color='CPI 2024 score',
    locations='ISO3',
    hover_name='Country / Territory',
    title='CPI 2024 Ranking',
    color_continuous_scale='Viridis'
)
fig_choropleth.update_layout(
    template='plotly_dark',
    coloraxis_colorbar=dict(
        title="CPI 2024 score",
        tickvals=[cpi_current['CPI 2024 score'].min(), cpi_average, cpi_current['CPI 2024 score'].max()],
        ticktext=["Highly Corrupt", f"Median {round(cpi_average, 2)}", "Very Clean"]
    )
)

fig_pca = px.scatter(
    df,
    x='PCA1',
    y='PCA2',
    color='Corruption_Level',
    hover_name='Country / Territory',
    title='PCA Projection of CPI Numeric Features',
    color_continuous_scale='Viridis'
)
fig_pca.update_layout(template='plotly_dark')

fig_trend_all = get_average_historical_figure()
fig_anim = px.choropleth(cpi_historical, locations='ISO3', color='CPI score', animation_frame='Year', color_continuous_scale='Viridis', title='CPI Over Time (Animated)', template='plotly_dark')

# Dash App
app = Dash(__name__, external_stylesheets=[dbc.themes.CYBORG])

app.layout = dbc.Container([
    html.H1(
        'Corruption Perception Index Dashboard',
        className='text-center my-4'),
    dcc.Tabs([
        dcc.Tab(label='Overview', children=[
            html.Br(),
            dcc.Markdown(
                get_insights(cpi_current),
                style={
                    'backgroundColor': '#222',
                    'padding': '1rem'
                }
            ),
            dcc.Graph(figure=fig_dist),
            dcc.Graph(figure=fig_scatter)
        ]),

        dcc.Tab(label='Сhoropleth Map', children=[
            html.Br(),
            html.P(
                '※ Lighter colors indicate less perceived corruption (better); darker colors indicate higher corruption (worse).',
                style={
                    'color': 'lightgray', 'padding': '0.5rem'
                }
            ),
            dcc.Graph(figure=fig_choropleth)
        ]),

        dcc.Tab(label='PCA Visualization', children=[
            html.Br(),
            html.P(
                'PCA1 (horizontal axis) is the linear combination of original variables that captures the single largest source of variation across countries.\n PCA2 (vertical axis) captures the next largest, orthogonal to PCA1.',
                style={
                    'color': 'lightgray', 'padding': '0.5rem'
                }
            ),
            dcc.Graph(figure=fig_pca)
        ]),

        dcc.Tab(label='Data Table', children=[
            html.Br(),
            dash_table.DataTable(
                columns=[{'name': i, 'id': i} for i in cpi_current.columns],
                data=cpi_current.to_dict('records'),
                page_size=15,
                style_table={'overflowX': 'auto'},
                style_header={
                    'backgroundColor': '#222',
                    'color': 'white'
                },
                style_cell={
                    'backgroundColor': '#111',
                    'color': 'white'
                }
            )
        ]),

        dcc.Tab(label='Historical Trends', children=[
            html.Br(),
            html.P(
                'Average CPI Score Over Time',
                style={
                    'color': 'white',
                    'fontSize': '18px'
                }
            ),
            dcc.Graph(figure=fig_trend_all),
            get_historical_insights_block()
        ])
    ])
], fluid=True)

if __name__ == '__main__':
    app.run(debug=False)