Py.Cafe

stichbury/

vizro-sales

Category and Sub-Category Sales Analysis

DocsPricing
  • 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
############ 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()