Py.Cafe

ramon.mur.novales/

Superstore dashboard

Superstore Data Insights

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
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
import vizro
from vizro import Vizro
import vizro.models as vm
import vizro.actions as va
import pandas as pd
import numpy as np
import vizro.plotly.express as px
from vizro.models.types import capture
from vizro.tables import dash_ag_grid, dash_data_table

def load_superstore_data():
    """Load the Superstore dataset from GitHub"""
    url = "https://raw.githubusercontent.com/WuCandice/Superstore-Sales-Analysis/main/dataset/Superstore%20Dataset.csv"
    df = pd.read_csv(url)
    
    # Clean and prepare data for JSON serialization
    for col in df.columns:
        if df[col].dtype == 'object':
            # Fill NaN values and convert to string
            df[col] = df[col].fillna('').astype(str)
        elif df[col].dtype in ['float64', 'int64']:
            # Fill NaN values for numeric columns
            df[col] = df[col].fillna(0)
        elif pd.api.types.is_datetime64_any_dtype(df[col]):
            # Convert datetime to string
            df[col] = df[col].dt.strftime('%Y-%m-%d').fillna('')
    
    # Remove any columns with complex data types
    df = df.select_dtypes(include=[np.number, 'object'])
    
    return df

@capture("graph")
def monthly_sales_profit_chart(data_frame, selected_categories=None):
    """Create monthly sales and profit line chart"""
    # Handle default case
    if selected_categories is None:
        selected_categories = list(data_frame['Category'].unique())

    selected_categories = [selected_categories]
    
    # Filter data by selected categories
    df_filtered = data_frame[data_frame['Category'].isin(selected_categories)]
    
    # Convert Order Date to datetime
    df_copy = df_filtered.copy()
    df_copy['Order Date'] = pd.to_datetime(df_copy['Order Date'])
    
    # Extract year-month
    df_copy['Year-Month'] = df_copy['Order Date'].dt.to_period('M')
    
    # Group by month and sum sales and profit
    monthly_data = df_copy.groupby('Year-Month').agg({
        'Sales': 'sum',
        'Profit': 'sum'
    }).reset_index()
    
    # Convert Period back to string for plotting
    monthly_data['Year-Month'] = monthly_data['Year-Month'].astype(str)
    
    # Melt the data for line chart
    monthly_melted = monthly_data.melt(
        id_vars=['Year-Month'], 
        value_vars=['Sales', 'Profit'],
        var_name='Metric',
        value_name='Amount'
    )
    
    # Create title based on selected categories
    if len(selected_categories) == 1:
        category_text = selected_categories[0]
    else:
        category_text = ", ".join(sorted(selected_categories))
    
    # Create dynamic title
    chart_title = f"Sales and Profit by Month - {category_text}"
    
    # Create the line chart
    fig = px.line(
        data_frame=monthly_melted,
        x="Year-Month",
        y="Amount",
        color="Metric",
        title=chart_title,
        labels={
            "Year-Month": "Month",
            "Amount": "Amount ($)",
            "Metric": "Metric"
        }
    )
    
    fig.update_layout(
        height=500,
        xaxis_title="Month",
        yaxis_title="Sales ($)",
        legend=dict(
            orientation="h",
            yanchor="bottom",
            y=-0.15,
            xanchor="center",
            x=0.5
        ),
        margin=dict(l=50, r=50, t=80, b=80)
    )
    
    fig.update_traces(line=dict(width=3))
    
    return fig

@capture("graph")
def monthly_sales_by_category_chart(data_frame):
    """Create monthly sales grouped bar chart by category"""
    # Convert Order Date to datetime
    df_copy = data_frame.copy()
    df_copy['Order Date'] = pd.to_datetime(df_copy['Order Date'])
    
    # Extract year-month
    df_copy['Year-Month'] = df_copy['Order Date'].dt.to_period('M')
    
    # Group by month and category, sum sales
    monthly_category_data = df_copy.groupby(['Year-Month', 'Category']).agg({
        'Sales': 'sum'
    }).reset_index()
    
    # Convert Period back to string for plotting
    monthly_category_data['Year-Month'] = monthly_category_data['Year-Month'].astype(str)
    
    # Create dynamic title with drill-down hint
    chart_title = f"Monthly Sales by Category - All Categories<br><sup>Click on a category bar to drill down to product details</sup>"
    
    # Create the grouped bar chart
    fig = px.bar(
        data_frame=monthly_category_data,
        x="Year-Month",
        y="Sales",
        color="Category",
        title=chart_title,
        labels={
            "Year-Month": "Month",
            "Sales": "Sales ($)",
            "Category": "Category"
        },
        custom_data=["Category"]
    )
    
    fig.update_layout(
        height=500,
        xaxis_title="Month",
        yaxis_title="Sales ($)",
        legend=dict(
            orientation="h",
            yanchor="bottom",
            y=-0.15,
            xanchor="center",
            x=0.5
        ),
        # barmode='group',
        title_y=0.95,
        margin=dict(l=50, r=50, t=100, b=80)
    )
    
    return fig

@capture("graph")
def monthly_sales_by_product_chart(data_frame, selected_category=None):
    """Create monthly sales stacked bar chart by product name for a specific category"""
    # Handle default case
    if selected_category is None:
        selected_category = sorted(data_frame['Category'].unique())[0]
    
    # Filter data by selected category
    df_filtered = data_frame[data_frame['Category'] == selected_category]
    
    # Convert Order Date to datetime
    df_copy = df_filtered.copy()
    df_copy['Order Date'] = pd.to_datetime(df_copy['Order Date'])
    
    # Extract year-month
    df_copy['Year-Month'] = df_copy['Order Date'].dt.to_period('M')
    
    # Group by month and product name, sum sales
    # Get top 10 products by total sales to avoid overcrowding
    top_products = df_copy.groupby('Product Name')['Sales'].sum().nlargest(10).index
    df_top_products = df_copy[df_copy['Product Name'].isin(top_products)]
    
    monthly_product_data = df_top_products.groupby(['Year-Month', 'Product Name']).agg({
        'Sales': 'sum'
    }).reset_index()
    
    # Convert Period back to string for plotting
    monthly_product_data['Year-Month'] = monthly_product_data['Year-Month'].astype(str)
    
    # Create dynamic title
    chart_title = f"Monthly Sales by Product - {selected_category} (Top 10 Products)"
    
    # Create the stacked bar chart
    fig = px.bar(
        data_frame=monthly_product_data,
        x="Year-Month",
        y="Sales",
        color="Product Name",
        title=chart_title,
        labels={
            "Year-Month": "Month",
            "Sales": "Sales ($)",
            "Product Name": "Product"
        }
    )
    
    fig.update_layout(
        height=500,
        xaxis_title="Month",
        yaxis_title="Sales ($)",
        legend=dict(
            orientation="v",
            yanchor="top",
            y=1,
            xanchor="left",
            x=1.02
        ),
        # barmode='stack',
        margin=dict(l=50, r=200, t=80, b=50)
    )
    
    return fig

# Load the data
superstore_data = load_superstore_data()
print(f"Loaded data with {len(superstore_data)} rows and {len(superstore_data.columns)} columns")
print("Column types:", superstore_data.dtypes)

# Get unique categories for the parameter selector
categories = sorted(superstore_data['Category'].unique())

@capture("table")
def superstore_table(data_frame):
    """Create a table for the superstore data"""
    return data_frame[:10][["Ship Mode"]]

# Define the dashboard
dashboard = vm.Dashboard(
    title="Superstore Dataset Dashboard",
    pages=[
        vm.Page(
            title="Raw Data",
            components=[
                vm.Table(
                    figure=dash_data_table(data_frame=superstore_data),
                )
            ]
        ),
        vm.Page(
            id="summaries-page",
            title="Summaries",
            controls=[
                vm.Parameter(
                    targets=["monthly-chart.selected_categories"],
                    id="category_filter",
                    selector=vm.Dropdown(
                        options=categories,
                        value=categories[0],
                        multi=False,
                        title="Select Category"
                    ),
                    show_in_url=True
                )
            ],
            components=[
                vm.Container(
                    layout=vm.Grid(grid=[[0, 1]]),
                    components=[
                        vm.Graph(
                            id="monthly-chart",
                            figure=monthly_sales_profit_chart(data_frame=superstore_data, selected_categories=categories[0])
                        ),
                        vm.Graph(
                            id="category-bar-chart",
                            figure=monthly_sales_by_category_chart(data_frame=superstore_data),
                            actions=[
                                va.set_control(control="category_filter", value="customdata[0]"),
                                va.set_control(control="product_category_filter", value="customdata[0]"),
                                # va.navigate_to(page="product-drill-down")
                            ]
                        )
                    ]
                )
            ]
        ),
        vm.Page(
            id="product-drill-down",
            title="Product Drill-Down",
            controls=[
                vm.Parameter(
                    targets=["product-bar-chart.selected_category"],
                    id="product_category_filter",
                    selector=vm.Dropdown(
                        options=categories,
                        value=categories[0],
                        multi=False,
                        title="Select Category for Product Breakdown"
                    ),
                    show_in_url=True
                )
            ],
            components=[
                vm.Graph(
                    id="product-bar-chart",
                    figure=monthly_sales_by_product_chart(data_frame=superstore_data, selected_category=categories[0])
                )
            ]
        )
    ]
)

# Build and run the dashboard
Vizro().build(dashboard).run()