Py.Cafe

parametrix/

sp_dashboard

status page dashboard testing

DocsPricing
  • app.py
  • dashboard_graph_data.pkl
  • distribution.pkl
  • requirements.txt
  • sp_data.pkl
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
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots

import vizro.models as vm
from vizro import Vizro
from vizro.models.types import capture

df = pd.read_pickle('dashboard_graph_data.pkl')
df2 = pd.read_pickle('distribution.pkl')

def build_hierarchical_dataframe(df, levels, name, cnt_column='count', pct_column='percentage', color_column=None):
    """
    Build a hierarchy of levels for Sunburst or Treemap charts.

    Levels are given starting from the bottom to the top of the hierarchy,
    i.e., the last level corresponds to the root.
    """
    df_list = []
    for i, level in enumerate(levels):
        df_tree = pd.DataFrame(columns=['id', 'parent', 'cnt', 'pct', 'color'])
        dfg = df.groupby(levels[i:]).sum()
        dfg = dfg.reset_index()
        df_tree['id'] = dfg[level].copy()
        if i < len(levels) - 1:
            df_tree['parent'] = dfg[levels[i + 1]].copy()
        else:
            df_tree['parent'] = 'total'
        df_tree['cnt'] = dfg[cnt_column]
        df_tree['pct'] = dfg[pct_column]
        if color_column:
            df_tree['color'] = dfg[color_column]
        else:
            df_tree['color'] = df_tree['pct'] * 1
        df_list.append(df_tree)
    total = pd.DataFrame([{
        'id': 'total', 
        'parent': '', 
        'cnt': df[cnt_column].sum(),
        'pct': 1.0,
        'color': 1,
    }])
    df_list.append(total)
    df_res = pd.concat(df_list, ignore_index=True)
    df_res['name'] = name
    return df_res

df_territory = build_hierarchical_dataframe(df2, ['country', 'territory'], 'territory')
df_industry = build_hierarchical_dataframe(df2, ['industry', 'industry_group'], 'industry')

df_distribution = pd.concat([df_territory, df_industry])

@capture("graph")
def create_graph(data_frame):
    """
    Create a Plotly figure from a unified DataFrame with specified colors for each platform.
    """
    # Define a color mapping for platforms
    platform_colors = {
        'AWS': 'blue',
        'Azure': 'red',
        'GCP': 'green',
        'Other': 'gray'
    }

    fig = go.Figure()

    # Loop through each platform and add a trace with its specified color
    for platform in data_frame['platform'].unique():
        platform_data = data_frame[data_frame['platform'] == platform]
        color = platform_colors.get(platform, 'black')  # Default to black if the platform is not in the mapping
        fig.add_trace(go.Scatter(
            x=platform_data['timestamp'],
            y=platform_data['count'],
            mode='lines',
            name=platform,
            hovertext=platform_data['hovertext'],
            hoverinfo='text',
            line=dict(color=color)
        ))

    fig.update_layout(
        title='Active Reports Over Time',
        xaxis=dict(
            title='Time',
            rangeslider=dict(visible=True),
            type='date'
        ),
        yaxis=dict(
            title='Reports',
            fixedrange=False
        ),
        legend=dict(
            orientation="h",
            yanchor="bottom",
            y=1.02,
            xanchor="right",
            x=1
        ),
        width=1200,
        height=700
    )
    return fig

@capture("graph")
def create_sunburst_chart(data_frame, title):
    """
    Create a nested pie chart using Plotly subplots.
    """
    df_territory = data_frame.query('name=="territory"')
    df_industry = data_frame.query('name=="industry"')

    fig = make_subplots(1, 2, specs=[[{"type": "domain"}, {"type": "domain"}]])

    fig.add_trace(go.Sunburst(
        labels=df_territory['id'],
        parents=df_territory['parent'],
        values=df_territory['cnt'],
        branchvalues='total',
        marker=dict(colors=df_territory['color'], colorscale='thermal'),
        name='',
        customdata=df_territory['pct'],
        texttemplate='%{label}<br>%{customdata:.1%}',
        hovertemplate='<b>%{label}</b><br>Count: %{value}<br>Percent: %{color:.2%}',
        maxdepth=3
    ), 1, 1)

    fig.add_trace(go.Sunburst(
        labels=df_industry['id'],
        parents=df_industry['parent'],
        values=df_industry['cnt'],
        branchvalues='total',
        marker=dict(colors=df_industry['color'], colorscale='thermal'),
        name='',
        customdata=df_industry['pct'],
        texttemplate='%{label}<br>%{customdata:.1%}',
        hovertemplate='<b>%{label}</b><br>Count: %{value}<br>Percent: %{color:.2%}',
        maxdepth=3
    ), 1, 2)

    fig.update_layout(
        title=title,
        width=1000,
        height=600,
        margin=dict(t=10, b=10, r=10, l=10),
    #     uniformtext=dict(minsize=10, mode='show'),
    #     uirevision=True
    )
    return fig

page_0 = vm.Page(
    title="Distribution Insights",
    components=[
        vm.Graph(
            id="sunburst",
            figure=create_sunburst_chart(
                data_frame=df_distribution,
                title='Status Pages Distribution by Territory and Industry'
            ),
        ),
    ]
)

page_1 = vm.Page(
    title="Active Report Count",
    components=[
        vm.Graph(
            id="active reports",
            figure=create_graph(data_frame=df),
        ),
    ]
)

dashboard = vm.Dashboard(pages=[page_0, page_1])

Vizro().build(dashboard).run()