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()