-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdashboard.py
297 lines (238 loc) · 8.57 KB
/
dashboard.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
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import streamlit as st
from babel.numbers import format_currency
sns.set(style='dark')
# create_daily_orders_df() digunakan untuk menyiapkan daily_orders_df.
def create_daily_orders_df(df):
daily_orders_df = df.resample(rule='D', on='order_date').agg({
"order_id": "nunique",
"total_price": "sum"
})
daily_orders_df = daily_orders_df.reset_index()
daily_orders_df.rename(columns={
"order_id": "order_count",
"total_price": "revenue"
}, inplace=True)
return daily_orders_df
# create_sum_order_items_df() bertanggung jawab untuk menyiapkan sum_orders_items_df.
def create_sum_order_items_df(df):
sum_order_items_df = df.groupby("product_name").quantity_x.sum().sort_values(ascending=False).reset_index()
return sum_order_items_df
# create_bygender_df() digunakan untuk menyiapkan bygender_df.
def create_bygender_df(df):
bygender_df = df.groupby(by="gender").customer_id.nunique().reset_index()
bygender_df.rename(columns={
"customer_id": "customer_count"
}, inplace=True)
return bygender_df
# create_byage_df() merupakan helper function yang digunakan untuk menyiapkan byage_df.
def create_byage_df(df):
byage_df = df.groupby(by="age_group").customer_id.nunique().reset_index()
byage_df.rename(columns={
"customer_id": "customer_count"
}, inplace=True)
byage_df['age_group'] = pd.Categorical(byage_df['age_group'], categories=["Youth", "Adults", "Seniors"])
return byage_df
# create_bystate_df() digunakan untuk menyiapkan bystate_df.
def create_bystate_df(df):
bystate_df = df.groupby(by="state").customer_id.nunique().reset_index()
bystate_df.rename(columns={
"customer_id": "customer_count"
}, inplace=True)
return bystate_df
# create_rfm_df() bertanggung jawab untuk menghasilkan rfm_df.
def create_rfm_df(df):
rfm_df = df.groupby(by="customer_id", as_index=False).agg({
"order_date": "max",
"order_id": "nunique",
"total_price": "sum"
})
rfm_df.columns = ["customer_id", "max_order_timestamp", "frequency", "monetary"]
rfm_df["max_order_timestamp"] = rfm_df["max_order_timestamp"].dt.date
recent_date = df["order_date"].dt.date.max()
rfm_df["recency"] = rfm_df["max_order_timestamp"].apply(lambda x: (recent_date - x).days)
rfm_df.drop("max_order_timestamp", axis=1, inplace=True)
return rfm_df
# Load cleaned data
all_df = pd.read_csv("all_data.csv")
datetime_columns = ["order_date", "delivery_date"]
all_df.sort_values(by="order_date", inplace=True)
all_df.reset_index(inplace=True)
for column in datetime_columns:
all_df[column] = pd.to_datetime(all_df[column])
# Filter data
min_date = all_df["order_date"].min()
max_date = all_df["order_date"].max()
with st.sidebar:
# Menambahkan logo perusahaan
st.image("/~https://github.com/dicodingacademy/assets/raw/main/logo.png")
# Mengambil start_date & end_date dari date_input
start_date, end_date = st.date_input(
label = 'Rentang Waktu',
min_value = min_date,
max_value = max_date,
value = [min_date, max_date]
)
main_df = all_df[(all_df["order_date"] >= str(start_date)) & (all_df["order_date"] <= str(end_date))]
# Menyiapakan berbagai dataframe
daily_orders_df = create_daily_orders_df(main_df)
sum_order_items_df = create_sum_order_items_df(main_df)
bygender_df = create_bygender_df(main_df)
byage_df = create_byage_df(main_df)
bystate_df = create_bystate_df(main_df)
rfm_df = create_rfm_df(main_df)
# plot number of daily orders (2021)
st.header('Dicoding Collection Dashboard :sparkles:')
st.subheader('Daily Orders')
col1, col2 = st.columns(2)
with col1:
total_orders = daily_orders_df["order_count"].sum()
st.metric("Total orders", value=total_orders)
with col2:
total_revenue = format_currency(daily_orders_df["revenue"].sum(), 'AUD', locale='es_CO')
st.metric("Total revenue", value=total_revenue)
fig, ax = plt.subplots(figsize=(16, 8))
ax.plot(
daily_orders_df["order_date"],
daily_orders_df["order_count"],
marker='o',
linewidth=2,
color="#90CAF9"
)
ax.tick_params(axis='y', labelsize=20)
ax.tick_params(axis='x', labelsize=15)
st.pyplot(fig)
# Product performance
st.subheader('Best & Worst Performing Products')
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(35, 15))
colors = ["#90CAF9", "#D3D3D3", "#D3D3D3", "#D3D3D3", "#D3D3D3"]
sns.barplot(
x="quantity_x",
y="product_name",
data=sum_order_items_df.head(5),
palette=colors,
ax=ax[0]
)
ax[0].set_ylabel(None)
ax[0].set_xlabel("Number of Sales", fontsize=30)
ax[0].set_title("Best Performing Products", loc="center", fontsize=50)
ax[0].tick_params(axis='y', labelsize=35)
ax[0].tick_params(axis='x', labelsize=30)
sns.barplot(
x="quantity_x",
y="product_name",
data=sum_order_items_df.sort_values(by="quantity_x", ascending=True).head(5),
palette=colors,
ax=ax[1]
)
ax[1].set_ylabel(None)
ax[1].set_xlabel("Number of Sales", fontsize=30)
ax[1].invert_xaxis()
ax[1].yaxis.set_label_position("right")
ax[1].yaxis.tick_right()
ax[1].set_title("Worst Performing Products", loc="center", fontsize=50)
ax[1].tick_params(axis='y', labelsize=35)
ax[1].tick_params(axis='x', labelsize=30)
st.pyplot(fig)
# Customer demographic
st.subheader('Customer Demographics')
col1, col2 = st.columns(2)
with col1:
fig, ax = plt.subplots(figsize=(20, 10))
sns.barplot(
y="customer_count",
x="gender",
data=bygender_df.sort_values(by="customer_count", ascending=False),
palette=colors,
ax=ax
)
ax.set_title("Number of Customers by Gender", loc="center", fontsize=50)
ax.set_ylabel(None)
ax.set_xlabel(None)
ax.tick_params(axis='x', labelsize=35)
ax.tick_params(axis='y', labelsize=30)
st.pyplot(fig)
with col2:
fig, ax = plt.subplots(figsize=(20, 10))
colors = ["#D3D3D3", "#90CAF9", "#D3D3D3", "#D3D3D3", "#D3D3D3"]
sns.barplot(
y="customer_count",
x="age_group",
data=byage_df.sort_values(by="age_group", ascending=False),
palette=colors,
ax=ax
)
ax.set_title("Number of Customers by Age", loc="center", fontsize=50)
ax.set_ylabel(None)
ax.set_xlabel(None)
ax.tick_params(axis='x', labelsize=35)
ax.tick_params(axis='y', labelsize=30)
st.pyplot(fig)
fig, ax = plt.subplots(figsize=(20, 10))
colors = ["#90CAF9", "#D3D3D3", "#D3D3D3", "#D3D3D3", "#D3D3D3", "#D3D3D3", "#D3D3D3", "#D3D3D3"]
sns.barplot(
x="customer_count",
y="state",
data=bystate_df.sort_values(by="customer_count", ascending=False),
palette=colors,
ax=ax
)
ax.set_title("Number of Customers by States", loc="center", fontsize=30)
ax.set_ylabel(None)
ax.set_xlabel(None)
ax.tick_params(axis='x', labelsize=20)
ax.tick_params(axis='y', labelsize=20)
st.pyplot(fig)
# Best Customers Based on RFM Parameters
st.subheader('Best Customers Based on RFM Parameters')
col1, col2, col3 = st.columns(3)
with col1:
avg_recency = round(rfm_df.recency.mean(), 1)
st.metric("Average Recency (days)", value=avg_recency)
with col2:
avg_frequency = round(rfm_df.frequency.mean(), 2)
st.metric("Average Frequency", value=avg_frequency)
with col3:
avg_monetary = format_currency(rfm_df.monetary.mean(), 'AUD', locale='es_CO')
st.metric("Average Monetary", value=avg_monetary)
fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(35, 15))
colors = ["#90CAF9", "#90CAF9", "#90CAF9", "#90CAF9", "#90CAF9"]
sns.barplot(
y="recency",
x="customer_id",
data=rfm_df.sort_values(by="recency", ascending=True).head(5), palette=colors,
ax=ax[0]
)
ax[0].set_ylabel(None)
ax[0].set_xlabel("customer_id", fontsize=30)
ax[0].set_title("By Recency (days)", loc="center", fontsize=50)
ax[0].tick_params(axis='y', labelsize=30)
ax[0].tick_params(axis='x', labelsize=35)
sns.barplot(
y="frequency",
x="customer_id",
data=rfm_df.sort_values(by="frequency", ascending=False).head(5),
palette=colors,
ax=ax[1]
)
ax[1].set_ylabel(None)
ax[1].set_xlabel("customer_id", fontsize=30)
ax[1].set_title("By Frequency", loc="center", fontsize=50)
ax[1].tick_params(axis='y', labelsize=30)
ax[1].tick_params(axis='x', labelsize=35)
sns.barplot(
y="monetary",
x="customer_id",
data=rfm_df.sort_values(by="monetary", ascending=False).head(5),
palette=colors,
ax=ax[2]
)
ax[2].set_ylabel(None)
ax[2].set_xlabel("customer_id", fontsize=30)
ax[2].set_title("By Monetary", loc="center", fontsize=50)
ax[2].tick_params(axis='y', labelsize=30)
ax[2].tick_params(axis='x', labelsize=35)
st.pyplot(fig)
st.caption('Copyright (c) Dicoding 2023')