✔ Copied

advanced_sales_wheel_9.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# advanced_sales_wheel_9.py
# Retail Sales Dashboard – Version 9
# Developed by Tryfon Papadopoulos – GitHub: trifpap
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Wedge
import textwrap

plt.style.use("seaborn-v0_8")

# -----------------------------
# Load Dataset
# -----------------------------

file = input("Enter sales file (csv or xlsx): ")

if file.endswith(".csv"):
    df = pd.read_csv(file)
elif file.endswith(".xlsx"):
    df = pd.read_excel(file)
else:
    raise ValueError("File must be CSV or XLSX")

df["Date"] = pd.to_datetime(df["Date"])

# -----------------------------
# KPI Calculations
# -----------------------------

total_sales_value = df["Sales"].sum()

category_sales_full = df.groupby("Category")["Sales"].sum().sort_values(ascending=False)

best_category = category_sales_full.idxmax()
best_category_sales = category_sales_full.max()

product_sales_full = df.groupby("Product")["Sales"].sum().sort_values(ascending=False)

best_product = product_sales_full.idxmax()
best_product_sales = product_sales_full.max()

# -----------------------------
# Top 6 Categories
# -----------------------------

top_categories = category_sales_full.head(6)
other_sales = category_sales_full.iloc[6:].sum()

category_sales = top_categories.copy()

if other_sales > 0:
    category_sales["Others"] = other_sales

subcategories = df.groupby("Category")["Subcategory"].unique()

# -----------------------------
# Helper
# -----------------------------

def wrap_text(text,width):
    return "\n".join(textwrap.wrap(str(text),width))

# -----------------------------
# Prepare Wheel Data
# -----------------------------

data = []

for category in category_sales.index:

    sales = category_sales[category]

    if category == "Others":
        subs = ["Multiple"]
    else:
        subs = subcategories[category]

    data.append((category,list(subs),sales))

total_sales = category_sales.sum()

# -----------------------------
# Dashboard Layout
# -----------------------------

#fig = plt.figure(figsize=(18,12))
# A4
fig = plt.figure(figsize=(16,11))
fig.patch.set_facecolor("#f5f5f5")

# charts moved lower for KPI space
ax_wheel  = fig.add_axes([0.03,0.22,0.47,0.50])
ax_bar    = fig.add_axes([0.56,0.62,0.40,0.20])
ax_line   = fig.add_axes([0.56,0.36,0.40,0.18])
ax_growth = fig.add_axes([0.56,0.08,0.40,0.20])
ax_labels = fig.add_axes([0.03,0.04,0.47,0.16])

ax_wheel.set_aspect("equal")

# -----------------------------
# Dashboard Title
# -----------------------------

fig.suptitle(
"Retail Sales Dashboard - Version 9 - Developed by Tryfon Papadopoulos",
fontsize=22,
weight="bold",
y=0.98
)

# -----------------------------
# KPI Cards
# -----------------------------

kpi_box = dict(
boxstyle="round,pad=0.9",
facecolor="#f2f2f2",
edgecolor="gray"
)

kpi_y = 0.87

fig.text(
0.15,kpi_y,
f"Total Sales\n${total_sales_value:,.0f}\n ",
fontsize=14,
weight="bold",
bbox=kpi_box,
ha="center"
)

fig.text(
0.50,kpi_y,
f"Top Category\n{best_category}\n${best_category_sales:,.0f}",
fontsize=14,
bbox=kpi_box,
ha="center"
)

fig.text(
0.85,kpi_y,
f"Best Product\n{best_product}\n${best_product_sales:,.0f}",
fontsize=14,
bbox=kpi_box,
ha="center"
)

# -----------------------------
# Chart 1 – Category Wheel
# -----------------------------

values = [d[2] for d in data]

angles = np.cumsum([0] + [v/total_sales*360 for v in values])

colors = list(plt.get_cmap("tab20").colors[:len(values)])

radius = 2.1
label_data = []

for i,(category,subs,sales) in enumerate(data):

    start = angles[i]
    end = angles[i+1]

    wedge = Wedge(
        (0,0),
        radius,
        start,
        end,
        facecolor=colors[i],
        edgecolor="white",
        linewidth=4
    )

    ax_wheel.add_patch(wedge)

    angle = (start+end)/2
    rad = np.deg2rad(angle)

    x = 0.60*radius*np.cos(rad)
    y = 0.60*radius*np.sin(rad)

    percent = sales/total_sales*100

    text = (
        f"{i+1}. {wrap_text(category,12)}\n"
        f"${sales:,.0f}\n"
        f"({percent:.1f}%)"
    )

    ax_wheel.text(
        x,y,text,
        ha="center",
        va="center",
        fontsize=11,
        weight="bold"
    )

    label_data.append(f"{i+1}. {category}{', '.join(subs)}")

ax_wheel.set_xlim(-2.4,2.4)
ax_wheel.set_ylim(-2.4,2.4)
ax_wheel.axis("off")

ax_wheel.set_title(
"Sales Distribution (Top Categories)",
fontsize=16,
weight="bold"
)

# -----------------------------------
# Chart 2: Top 10 Products by Sales
# -----------------------------------

top_products = (
    df.groupby(["Product", "Category", "Subcategory"])["Sales"]
    .sum()
    .sort_values(ascending=False)
    .head(10)
    .reset_index()
)

# Create multi-line label
top_products["Label"] = (
    top_products["Product"]
    + "\n("
    + top_products["Category"]
    + " → "
    + top_products["Subcategory"]
    + ")"
)

# Wrap long labels
#top_products["Label"] = top_products["Label"].apply(lambda x: wrap_text(x,25))
top_products["Label"] = top_products["Label"].apply(lambda x: wrap_text(x,35))

labels = list(top_products["Label"][::-1])
values = list(top_products["Sales"][::-1])

# Create spacing between bars
y_pos = np.arange(len(labels)) * 2.4

bars = ax_bar.barh(
    y_pos,
    values,
    height=1.9,
    color="steelblue"
)

# Apply labels
ax_bar.set_yticks(y_pos)
ax_bar.set_yticklabels(labels)

# Improve label formatting
for label in ax_bar.get_yticklabels():
    label.set_horizontalalignment("right")
    label.set_linespacing(1.0)

# Add space between labels and bars
ax_bar.tick_params(axis="y", pad=10, labelsize=8)

# Value labels inside bars
for bar in bars:

    width = bar.get_width()

    ax_bar.text(
        width * 0.97,
        bar.get_y() + bar.get_height()/2,
        f"${width:,.0f}",
        ha="right",
        va="center",
        color="white",
        fontsize=10,
        weight="bold"
    )

# Titles and formatting
ax_bar.set_title("Top 10 Products by Sales", fontsize=14)
ax_bar.set_xlabel("Sales")

ax_bar.set_xlim(0, max(values) * 1.10)

# Add subtle grid
ax_bar.grid(axis="x", linestyle="--", alpha=0.4)

# -----------------------------
# Chart 3 – Monthly Trend
# -----------------------------

monthly_sales = df.resample("ME",on="Date")["Sales"].sum()

ax_line.plot(monthly_sales.index,monthly_sales.values,marker="o")

ax_line.fill_between(
monthly_sales.index,
monthly_sales.values,
alpha=0.2
)

ax_line.set_title("Monthly Sales Trend")
ax_line.set_xlabel("Month")
ax_line.set_ylabel("Sales")

ax_line.grid(True,linestyle="--",alpha=0.5)

# -----------------------------
# Chart 4 – Category Growth
# -----------------------------

monthly_category = df.groupby(
[pd.Grouper(key="Date",freq="ME"),"Category"]
)["Sales"].sum().unstack()

growth = monthly_category.pct_change().mean().sort_values(ascending=False)

ax_growth.bar(
growth.index,
growth.values,
color="orange"
)

ax_growth.set_title("Category Growth Rate")
ax_growth.set_ylabel("Growth %")

ax_growth.tick_params(axis="x",rotation=45)

# -----------------------------
# Category Details
# -----------------------------

ax_labels.axis("off")

ax_labels.text(
#0.01,
0.06,
0.90,
"Category Details",
fontsize=13,
weight="bold"
)

half = len(label_data)//2 + len(label_data)%2

left = label_data[:half]
right = label_data[half:]

for i,text in enumerate(left):

    ax_labels.text(
        #0.01,
        0.06,    
        0.70 - i*0.18,
        wrap_text(text,40),
        fontsize=11
    )

for i,text in enumerate(right):

    ax_labels.text(
        #0.50,
        0.56,
        0.70 - i*0.18,
        wrap_text(text,40),
        fontsize=11
    )

# -----------------------------
# Save Dashboard
# -----------------------------

# Save PNG
plt.savefig(
"retail_sales_dashboard.png",
dpi=300,
bbox_inches="tight"
)

# Save PDF
plt.savefig(
"retail_sales_dashboard.pdf",
bbox_inches="tight"
)

print("Dashboard saved as: retail_sales_dashboard.png and retail_sales_dashboard.pdf")

plt.show()