Py.Cafe

stichbury/

megastore-sales-profit-analysis

Megastore Sales & Profit 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
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
############ 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
import numpy as np
from vizro.models.types import capture


####### Function definitions ######
@capture("graph")
def horizontal_category_subcategory_sales(data_frame):
    # Define low volume stationery subcategories to combine
    low_volume_items = [
        "Envelopes",
        "Pens & Art Supplies",
        "Scissors, Rulers and Trimmers",
        "Labels",
        "Rubber Bands",
    ]

    # Create a copy of the dataframe for processing
    df_processed = data_frame.copy()

    # Replace the low volume subcategories with 'Low volume stationery'
    df_processed.loc[
        df_processed["Product Sub-Category"].isin(low_volume_items),
        "Product Sub-Category",
    ] = "Low volume stationery"

    # Group by Product Category and Product Sub-Category to get total sales and profit
    grouped = (
        df_processed.groupby(["Product Category", "Product Sub-Category"])
        .agg({"Sales": "sum", "Profit": "sum"})
        .reset_index()
    )

    # Calculate Profit Margin as sum(profit)/sum(sales) for each row
    grouped["Profit Margin"] = grouped["Profit"] / grouped["Sales"]

    # Sort by Product Category, then by Sales DESCENDING within each category (highest first)
    grouped = grouped.sort_values(
        ["Product Category", "Sales"], ascending=[True, False]
    )

    # Normalize profit margin values for color mapping (0 to 1 scale)
    min_margin = grouped["Profit Margin"].min()
    max_margin = grouped["Profit Margin"].max()
    margin_range = max_margin - min_margin

    # Create color scale from pale blue (low profit margin) to dark blue (high profit margin)
    def get_color(margin_value):
        if margin_range == 0:
            return "#1f4e79"  # Default dark blue if no variation

        # Normalize margin to 0-1 scale
        normalized = (margin_value - min_margin) / margin_range

        # Interpolate between pale blue and dark blue
        # Pale Blue: #add8e6, Dark Blue: #1f4e79
        pale_r, pale_g, pale_b = 173, 216, 230
        dark_r, dark_g, dark_b = 31, 78, 121

        r = int(pale_r + (dark_r - pale_r) * normalized)
        g = int(pale_g + (dark_g - pale_g) * normalized)
        b = int(pale_b + (dark_b - pale_b) * normalized)

        return f"rgb({r},{g},{b})"

    # Create colors for each bar based on profit margin
    colors = [get_color(margin) for margin in grouped["Profit Margin"]]

    # Create y-axis labels that maintain the sorted order (reverse for plotly display)
    y_labels = grouped["Product Sub-Category"].tolist()
    y_labels.reverse()  # Reverse so highest sales appear at top

    fig = go.Figure()

    # Reverse the data order for display (highest sales at top)
    grouped_reversed = grouped.iloc[::-1].reset_index(drop=True)
    colors_reversed = colors[::-1]

    fig.add_trace(
        go.Bar(
            y=grouped_reversed["Product Sub-Category"],
            x=grouped_reversed["Sales"],
            orientation="h",
            marker=dict(
                color=colors_reversed,
                line=dict(width=0.5, color="rgba(255,255,255,0.4)"),
            ),
            hovertemplate="<b>%{y}</b><br>Sales: $%{x:,.0f}<br>Profit: $%{customdata[0]:,.0f}<br>Profit Margin: %{customdata[1]:.1%}<br><extra></extra>",
            customdata=list(
                zip(grouped_reversed["Profit"], grouped_reversed["Profit Margin"])
            ),
            name="Sales by Sub-Category",
        )
    )

    # Add dividing lines between product categories (adjust for reversed order)
    categories = grouped["Product Category"].unique()
    total_items = len(grouped)
    y_position = 0

    for i, category in enumerate(categories):
        category_count = len(grouped[grouped["Product Category"] == category])

        # Calculate position from bottom for reversed display
        if i > 0:
            line_position = total_items - y_position - 0.5
            fig.add_hline(
                y=line_position,
                line=dict(color="rgba(255,255,255,0.6)", width=2, dash="solid"),
            )

        y_position += category_count

    # Create gradient bar for legend
    gradient_x = np.linspace(0, 1, 100)
    gradient_colors = [
        get_color(min_margin + (max_margin - min_margin) * x) for x in gradient_x
    ]

    # Add gradient bar as a separate subplot area
    fig.add_trace(
        go.Bar(
            x=gradient_x,
            y=["Profit Margin"] * 100,
            orientation="h",
            marker=dict(color=gradient_colors, line=dict(width=0)),
            showlegend=False,
            hoverinfo="skip",
            yaxis="y2",
            xaxis="x2",
        )
    )

    fig.update_layout(
        xaxis_title="Sales ($)",
        yaxis_title="Product Sub-Category",
        height=800,
        hovermode="closest",
        paper_bgcolor="rgba(0,0,0,0)",
        plot_bgcolor="rgba(0,0,0,0)",
        showlegend=False,
        yaxis=dict(categoryorder="array", categoryarray=y_labels, domain=[0, 0.85]),
        # Second y-axis for gradient legend
        yaxis2=dict(
            domain=[0.9, 0.95],
            anchor="x2",
            showticklabels=False,
            showgrid=False,
            zeroline=False,
        ),
        # Second x-axis for gradient legend
        xaxis2=dict(
            domain=[0.7, 0.98],
            anchor="y2",
            showticklabels=False,
            showgrid=False,
            zeroline=False,
        ),
        annotations=[
            # Gradient legend labels
            dict(
                x=0.68,
                y=0.925,
                xref="paper",
                yref="paper",
                text="Low Margin",
                showarrow=False,
                font=dict(size=10, color="white"),
                xanchor="right",
            ),
            dict(
                x=1.0,
                y=0.925,
                xref="paper",
                yref="paper",
                text="High Margin",
                showarrow=False,
                font=dict(size=10, color="white"),
                xanchor="left",
            ),
            dict(
                x=0.84,
                y=0.97,
                xref="paper",
                yref="paper",
                text="<b>Profit Margin</b>",
                showarrow=False,
                font=dict(size=11, color="white"),
                xanchor="center",
            ),
        ],
    )

    return fig


####### Data Manager Settings #####
data_manager["megastore_data"] = pd.read_csv(
    "https://raw.githubusercontent.com/stichbury/vizro_projects/main/Megastore/MegastoreData.csv"
)

########### Model code ############
model = vm.Dashboard(
    pages=[
        vm.Page(
            components=[
                vm.Graph(
                    id="sales_chart",
                    type="graph",
                    figure=horizontal_category_subcategory_sales(
                        data_frame="megastore_data"
                    ),
                    title="Sales by Product Sub-Category (Color = Profit Margin)",
                )
            ],
            title="Megastore Sales Analysis",
            controls=[
                vm.Filter(
                    type="filter",
                    column="Continent",
                    targets=["sales_chart"],
                    selector=vm.Dropdown(
                        type="dropdown",
                        value=["Asia", "Europe", "North America", "South America"],
                        multi=True,
                    ),
                )
            ],
        )
    ],
    theme="vizro_dark",
    title="Megastore Dashboard",
)

Vizro().build(model).run()