############ Imports ##############
import vizro.models as vm
from vizro.models.types import capture
from vizro import Vizro
import pandas as pd
from vizro.managers import data_manager
import plotly.graph_objects as go
from vizro.models.types import capture
####### Function definitions ######
@capture("graph")
def horizontal_category_subcategory_sales(data_frame):
# Group by Product Category and Product Sub-Category to get total sales
grouped = (
data_frame.groupby(["Product Category", "Product Sub-Category"])["Sales"]
.sum()
.reset_index()
)
fig = go.Figure()
# Get unique categories and assign colors
categories = grouped["Product Category"].unique()
colors = ["#1f77b4", "#ff7f0e", "#2ca02c"] # Blue, Orange, Green
for i, category in enumerate(categories):
category_data = grouped[grouped["Product Category"] == category]
fig.add_trace(
go.Bar(
y=category_data["Product Sub-Category"],
x=category_data["Sales"],
name=category,
orientation="h",
marker=dict(color=colors[i % len(colors)]),
hovertemplate="<b>%{fullData.name}</b><br>Sub-Category: %{y}<br>Sales: $%{x:,.0f}<br><extra></extra>",
)
)
fig.update_layout(
xaxis_title="Sales ($)",
yaxis_title="Product Sub-Category",
barmode="stack",
height=800,
hovermode="closest",
paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)",
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
)
return fig
####### Data Manager Settings #####
data_manager["megastore_data"] = pd.read_excel(
"https://raw.githubusercontent.com/stichbury/vizro_projects/main/Megastore/MegastoreData.xlsx"
)
########### Model code ############
model = vm.Dashboard(
pages=[
vm.Page(
components=[
vm.Graph(
type="graph",
figure=horizontal_category_subcategory_sales(
data_frame="megastore_data"
),
title="Sales by Product Category and Sub-Category",
)
],
title="Megastore Sales Analysis",
)
],
theme="vizro_dark",
title="Megastore Dashboard",
)
Vizro().build(model).run()