Skip to content

Commit 3270feb

Browse files
Updated Professional_Dashboard_Plotly.ipynb with new content
1 parent 81abe35 commit 3270feb

File tree

1 file changed

+1
-388
lines changed

1 file changed

+1
-388
lines changed
Lines changed: 1 addition & 388 deletions
Original file line numberDiff line numberDiff line change
@@ -1,388 +1 @@
1-
{
2-
"cells": [
3-
{
4-
"cell_type": "markdown",
5-
"metadata": {},
6-
"source": [
7-
"# Dashboard Profissional Python/Plotly — Implementação Completa\n",
8-
"\n",
9-
"Este notebook implementa, passo a passo, um dashboard interativo com múltiplos gráficos e filtros, seguindo as melhores práticas do repositório [Python-Data-Plotly-Predictive-Analytics-Dashboard](https://github.com/Genovese-Felipe/Python-Data-Plotly-Predictive-Analytics-Dashboard). O objetivo é garantir excelência visual, performance, responsividade e interatividade profissional.\n",
10-
"\n",
11-
"**Referências cruzadas:**\n",
12-
"- `README.md` (estrutura e narrativa)\n",
13-
"- `Knowledge-Base/03_Technical_Documentation/Official_Plotly_Dash_Docs/`\n",
14-
"- `Professional Practices and Tips`\n",
15-
"- `scripts/viz_new.py`\n",
16-
"- `prompt_modelo.md` e `business_prompt.md` (storytelling)\n",
17-
"- `requirements_processing.txt` (dependências)\n",
18-
"- `DASHBOARD_EXECUTION_SUCCESS_REPORT.md` e `FINAL_STATUS_CHECK.md` (validação)\n",
19-
"\n",
20-
"**Execução:** \n",
21-
"1. Instale as dependências indicadas.\n",
22-
"2. Execute cada célula sequencialmente.\n",
23-
"3. O dashboard estará disponível na saída ao final do notebook (Colab) ou em [http://localhost:8050](http://localhost:8050) (Codespace/Jupyter)."
24-
]
25-
},
26-
{
27-
"cell_type": "markdown",
28-
"metadata": {},
29-
"source": [
30-
"---\n",
31-
"# 1️⃣ PASSO 1: Setup de Ambiente e Importação de Bibliotecas\n",
32-
"\n",
33-
"Siga este passo tanto em Colab quanto Codespace para garantir o ambiente correto. Execute a célula abaixo **apenas uma vez** para instalar as dependências."
34-
]
35-
},
36-
{
37-
"cell_type": "code",
38-
"metadata": {},
39-
"source": [
40-
"# Instale os pacotes necessários (descomente se necessário)\n",
41-
"# Colab já inclui grande parte, mas garanta as versões certas:\n",
42-
"!pip install -q dash==2.14.2 dash-bootstrap-components plotly pandas numpy jupyter-dash\n",
43-
"import warnings\n",
44-
"warnings.filterwarnings('ignore')"
45-
]
46-
},
47-
{
48-
"cell_type": "code",
49-
"metadata": {},
50-
"source": [
51-
"# Importação das bibliotecas principais\n",
52-
"import pandas as pd\n",
53-
"import numpy as np\n",
54-
"import plotly.graph_objects as go\n",
55-
"import plotly.express as px\n",
56-
"from dash import dcc, html, Input, Output, State, callback_context\n",
57-
"import dash_bootstrap_components as dbc\n",
58-
"from dash.exceptions import PreventUpdate\n",
59-
"\n",
60-
"try:\n",
61-
" from jupyter_dash import JupyterDash\n",
62-
"except ImportError:\n",
63-
" !pip install jupyter-dash\n",
64-
" from jupyter_dash import JupyterDash\n",
65-
"\n",
66-
"print(\"✅ Bibliotecas importadas com sucesso!\")"
67-
]
68-
},
69-
{
70-
"cell_type": "markdown",
71-
"metadata": {},
72-
"source": [
73-
"---\n",
74-
"# 2️⃣ PASSO 2: Geração e Estruturação dos Dados Sintéticos\n",
75-
"\n",
76-
"**Colunas:** Category, Cause, Site, Month, Year, Severity, Status, Count\n",
77-
"\n",
78-
"Os dados são gerados de modo a cobrir todas as dimensões do dashboard, com realismo e variedade para os filtros e gráficos."
79-
]
80-
},
81-
{
82-
"cell_type": "code",
83-
"metadata": {},
84-
"source": [
85-
"# Parâmetros principais\n",
86-
"categories = ['Customer', 'Spill', 'Injury', 'Transport', 'Equipment', 'Security', 'Divergence', 'Complaint']\n",
87-
"causes = ['Material', 'Procedure', 'Design', 'Training', 'Management', 'External', 'Equipment', 'Personnel']\n",
88-
"sites = ['Weston', 'Bolton', 'Shirley', 'Lincoln', 'Maynard', 'Acton', 'Concord', 'Hudson']\n",
89-
"months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n",
90-
"years = [2007, 2008, 2009]\n",
91-
"severities = ['Critical', 'Major', 'Medium', 'Near Miss']\n",
92-
"status = ['Open', 'Closed']\n",
93-
"\n",
94-
"np.random.seed(42)\n",
95-
"records = []\n",
96-
"for year in years:\n",
97-
" for month in months:\n",
98-
" for site in sites:\n",
99-
" for category in categories:\n",
100-
" for cause in np.random.choice(causes, size=2, replace=False):\n",
101-
" severity = np.random.choice(severities)\n",
102-
" stat = np.random.choice(status, p=[0.3, 0.7])\n",
103-
" count = np.random.poisson(lam=8)\n",
104-
" if count == 0:\n",
105-
" continue\n",
106-
" records.append({\n",
107-
" 'Category': category,\n",
108-
" 'Cause': cause,\n",
109-
" 'Site': site,\n",
110-
" 'Month': month,\n",
111-
" 'Year': year,\n",
112-
" 'Severity': severity,\n",
113-
" 'Status': stat,\n",
114-
" 'Count': count\n",
115-
" })\n",
116-
"\n",
117-
"df = pd.DataFrame(records)\n",
118-
"print(f\"✅ Dados gerados! Total de registros: {len(df)}\")\n",
119-
"df.head()"
120-
]
121-
},
122-
{
123-
"cell_type": "markdown",
124-
"metadata": {},
125-
"source": [
126-
"---\n",
127-
"# 3️⃣ PASSO 3: Design do Layout do Dashboard\n",
128-
"\n",
129-
"- Grid: 2 linhas × 3 colunas para os gráficos, sidebar à direita com filtros.\n",
130-
"- Responsividade e visual clean (PatternFly/Plotly palette)."
131-
]
132-
},
133-
{
134-
"cell_type": "code",
135-
"metadata": {},
136-
"source": [
137-
"# Paleta profissional\n",
138-
"COLORS = {\n",
139-
" 'primary': '#1f77b4', # Azul\n",
140-
" 'success': '#2ca02c', # Verde\n",
141-
" 'warning': '#ff7f0e', # Laranja\n",
142-
" 'danger': '#d62728', # Vermelho\n",
143-
" 'info': '#17becf', # Ciano\n",
144-
" 'secondary': '#7f7f7f', # Cinza\n",
145-
" 'background': '#f8f9fa',\n",
146-
" 'card_bg': '#fff',\n",
147-
" 'text_primary': '#212529',\n",
148-
" 'text_secondary': '#6c757d'\n",
149-
"}\n",
150-
"\n",
151-
"# Inicialização do app para Colab/Jupyter (JupyterDash)\n",
152-
"app = JupyterDash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])\n",
153-
"\n",
154-
"app.layout = dbc.Container(fluid=True, style={'backgroundColor': COLORS['background'], 'padding': '12px'}, children=[\n",
155-
" dbc.Row([\n",
156-
" dbc.Col([\n",
157-
" dbc.Row([\n",
158-
" dbc.Col([\n",
159-
" html.Div([\n",
160-
" html.H4(\"Category\", className=\"text-center\", style={'fontWeight': 'bold'}),\n",
161-
" dcc.Graph(id='bar-category')\n",
162-
" ])\n",
163-
" ], width=4),\n",
164-
" dbc.Col([\n",
165-
" html.Div([\n",
166-
" html.H4(\"Cause\", className=\"text-center\", style={'fontWeight': 'bold'}),\n",
167-
" dcc.Graph(id='bar-cause')\n",
168-
" ])\n",
169-
" ], width=4),\n",
170-
" dbc.Col([\n",
171-
" html.Div([\n",
172-
" html.H4(\"Month\", className=\"text-center\", style={'fontWeight': 'bold'}),\n",
173-
" dcc.Graph(id='line-month')\n",
174-
" ])\n",
175-
" ], width=4),\n",
176-
" ])\n",
177-
" ], width=10),\n",
178-
" dbc.Col([\n",
179-
" html.Div([\n",
180-
" html.H5(\"Filtros\", style={'fontWeight': 'bold', 'marginBottom': '8px'}),\n",
181-
" html.Label(\"Category\"), dcc.Dropdown(id=\"filter-category\", multi=True),\n",
182-
" html.Label(\"Site\"), dcc.Dropdown(id=\"filter-site\", multi=True),\n",
183-
" html.Label(\"Month\"), dcc.Dropdown(id=\"filter-month\", multi=True),\n",
184-
" html.Label(\"Cause\"), dcc.Dropdown(id=\"filter-cause\", multi=True),\n",
185-
" html.Label(\"Severity\"), dcc.Dropdown(id=\"filter-severity\", multi=True),\n",
186-
" html.Label(\"Year\"), dcc.Dropdown(id=\"filter-year\", multi=True),\n",
187-
" html.Label(\"Status\"), dcc.Dropdown(id=\"filter-status\", multi=True),\n",
188-
" html.Hr(),\n",
189-
" html.Div(\"Total de registros filtrados:\", style={'marginTop':'12px'}),\n",
190-
" html.H5(id=\"filtered-count\", style={'color': COLORS['primary'], 'fontWeight': 'bold'})\n",
191-
" ], style={'background': COLORS['card_bg'], 'padding': '16px', 'borderRadius': '8px', 'boxShadow': '0 2px 8px #e3e3e3'})\n",
192-
" ], width=2)\n",
193-
" ]),\n",
194-
"\n",
195-
" dbc.Row([\n",
196-
" dbc.Col([\n",
197-
" dbc.Row([\n",
198-
" dbc.Col([\n",
199-
" html.Div([\n",
200-
" html.H4(\"Site\", className=\"text-center\", style={'fontWeight': 'bold'}),\n",
201-
" dcc.Graph(id='bar-site')\n",
202-
" ])\n",
203-
" ], width=4),\n",
204-
" dbc.Col([\n",
205-
" html.Div([\n",
206-
" html.H4(\"Trend\", className=\"text-center\", style={'fontWeight': 'bold'}),\n",
207-
" dcc.Graph(id='bar-trend')\n",
208-
" ])\n",
209-
" ], width=4),\n",
210-
" dbc.Col([\n",
211-
" html.Div([\n",
212-
" html.H4(\"Severity\", className=\"text-center\", style={'fontWeight': 'bold'}),\n",
213-
" dcc.Graph(id='pie-severity')\n",
214-
" ])\n",
215-
" ], width=4),\n",
216-
" ])\n",
217-
" ], width=10),\n",
218-
" dbc.Col([], width=2)\n",
219-
" ])\n",
220-
"])\n",
221-
"\n",
222-
"print(\"✅ Layout estruturado. Pronto para conectar dados e gráficos!\")"
223-
]
224-
},
225-
{
226-
"cell_type": "markdown",
227-
"metadata": {},
228-
"source": [
229-
"---\n",
230-
"# 4️⃣ PASSO 4: Implementação dos Gráficos e Filtros Dinâmicos\n",
231-
"\n",
232-
"- Os filtros são preenchidos dinamicamente a partir dos dados.\n",
233-
"- Todos os gráficos e o contador são atualizados conforme qualquer filtro (crossfiltering).\n",
234-
"- Cada gráfico usa componentes Plotly Express/Graph Objects para máxima customização."
235-
]
236-
},
237-
{
238-
"cell_type": "code",
239-
"metadata": {},
240-
"source": [
241-
"# Função para preencher opções dos filtros com base nos dados\n",
242-
"def get_dropdown_options(col):\n",
243-
" opts = [{'label': str(i), 'value': i} for i in sorted(df[col].unique())]\n",
244-
" return opts\n",
245-
"\n",
246-
"# Callback para preencher todos os filtros ao carregar\n",
247-
"@app.callback(\n",
248-
" [Output(\"filter-category\", \"options\"),\n",
249-
" Output(\"filter-site\", \"options\"),\n",
250-
" Output(\"filter-month\", \"options\"),\n",
251-
" Output(\"filter-cause\", \"options\"),\n",
252-
" Output(\"filter-severity\", \"options\"),\n",
253-
" Output(\"filter-year\", \"options\"),\n",
254-
" Output(\"filter-status\", \"options\")],\n",
255-
" Input(\"filter-category\", \"id\")\n",
256-
")\n",
257-
"def fill_filter_options(_):\n",
258-
" return (\n",
259-
" get_dropdown_options(\"Category\"),\n",
260-
" get_dropdown_options(\"Site\"),\n",
261-
" get_dropdown_options(\"Month\"),\n",
262-
" get_dropdown_options(\"Cause\"),\n",
263-
" get_dropdown_options(\"Severity\"),\n",
264-
" get_dropdown_options(\"Year\"),\n",
265-
" get_dropdown_options(\"Status\"),\n",
266-
" )\n",
267-
"\n",
268-
"# Callback principal para atualizar todos os gráficos e contador\n",
269-
"@app.callback(\n",
270-
" [Output('bar-category', 'figure'),\n",
271-
" Output('bar-cause', 'figure'),\n",
272-
" Output('line-month', 'figure'),\n",
273-
" Output('bar-site', 'figure'),\n",
274-
" Output('bar-trend', 'figure'),\n",
275-
" Output('pie-severity', 'figure'),\n",
276-
" Output('filtered-count', 'children')],\n",
277-
" [Input('filter-category', 'value'),\n",
278-
" Input('filter-site', 'value'),\n",
279-
" Input('filter-month', 'value'),\n",
280-
" Input('filter-cause', 'value'),\n",
281-
" Input('filter-severity', 'value'),\n",
282-
" Input('filter-year', 'value'),\n",
283-
" Input('filter-status', 'value')]\n",
284-
")\n",
285-
"def update_all_graphs(cat, site, month, cause, severity, year, stat):\n",
286-
" dff = df.copy()\n",
287-
" if cat: dff = dff[dff['Category'].isin(cat)]\n",
288-
" if site: dff = dff[dff['Site'].isin(site)]\n",
289-
" if month: dff = dff[dff['Month'].isin(month)]\n",
290-
" if cause: dff = dff[dff['Cause'].isin(cause)]\n",
291-
" if severity: dff = dff[dff['Severity'].isin(severity)]\n",
292-
" if year: dff = dff[dff['Year'].isin(year)]\n",
293-
" if stat: dff = dff[dff['Status'].isin(stat)]\n",
294-
" total_count = int(dff['Count'].sum())\n",
295-
"\n",
296-
" def stacked_bar(data, x, color, orientation='v'):\n",
297-
" if orientation == 'v':\n",
298-
" fig = px.bar(data, x=x, y='Count', color=color, barmode='stack',\n",
299-
" color_discrete_sequence=px.colors.qualitative.Plotly)\n",
300-
" else:\n",
301-
" fig = px.bar(data, y=x, x='Count', color=color, barmode='stack',\n",
302-
" orientation='h', color_discrete_sequence=px.colors.qualitative.Plotly)\n",
303-
" fig.update_layout(title='', legend_title='', margin=dict(t=18, b=6, l=2, r=2),\n",
304-
" plot_bgcolor=COLORS['card_bg'], paper_bgcolor=COLORS['card_bg'])\n",
305-
" return fig\n",
306-
"\n",
307-
" # Gráfico 1: Category\n",
308-
" fig_cat = stacked_bar(dff, x='Category', color='Severity')\n",
309-
" # Gráfico 2: Cause\n",
310-
" fig_cause = stacked_bar(dff, x='Cause', color='Severity')\n",
311-
" # Gráfico 3: Linha temporal (Month)\n",
312-
" dff_line = dff.groupby(['Year', 'Month', 'Category'], as_index=False)['Count'].sum()\n",
313-
" dff_line['MonthNum'] = dff_line['Month'].apply(lambda m: months.index(m))\n",
314-
" dff_line = dff_line.sort_values(['Year', 'MonthNum'])\n",
315-
" fig_line = go.Figure()\n",
316-
" for cat_name in dff_line['Category'].unique():\n",
317-
" sub = dff_line[dff_line['Category'] == cat_name]\n",
318-
" x = sub['Year'].astype(str) + '-' + sub['Month']\n",
319-
" fig_line.add_trace(go.Scatter(x=x, y=sub['Count'], mode='lines+markers', name=cat_name))\n",
320-
" fig_line.update_layout(title='', xaxis_title='', yaxis_title='Count', legend_title='',\n",
321-
" margin=dict(t=18, b=6, l=2, r=2), plot_bgcolor=COLORS['card_bg'], paper_bgcolor=COLORS['card_bg'])\n",
322-
"\n",
323-
" # Gráfico 4: Barra empilhada horizontal (Site)\n",
324-
" fig_site = stacked_bar(dff, x='Site', color='Severity', orientation='h')\n",
325-
" # Gráfico 5: Barra empilhada horizontal (Trend por mês)\n",
326-
" fig_trend = stacked_bar(dff, x='Month', color='Severity', orientation='h')\n",
327-
" # Gráfico 6: Pizza (Severity)\n",
328-
" dff_pie = dff.groupby('Severity', as_index=False)['Count'].sum()\n",
329-
" fig_pie = px.pie(dff_pie, names='Severity', values='Count', color='Severity',\n",
330-
" color_discrete_sequence=px.colors.qualitative.Plotly)\n",
331-
" fig_pie.update_layout(title='', legend_title='', margin=dict(t=18, b=6, l=2, r=2),\n",
332-
" plot_bgcolor=COLORS['card_bg'], paper_bgcolor=COLORS['card_bg'])\n",
333-
"\n",
334-
" return fig_cat, fig_cause, fig_line, fig_site, fig_trend, fig_pie, f\"{total_count:,}\"\n",
335-
"\n",
336-
"print(\"✅ Gráficos e filtros prontos, aguardando execução do app.\")"
337-
]
338-
},
339-
{
340-
"cell_type": "markdown",
341-
"metadata": {},
342-
"source": [
343-
"---\n",
344-
"# 5️⃣ PASSO 5: Execução, Validação Final e Instruções de Uso\n",
345-
"\n",
346-
"**Em Colab/Jupyter, o dashboard será exibido abaixo desta célula após executar.**\n",
347-
"\n",
348-
"Checklist Final:\n",
349-
"- Bibliotecas instaladas? ✅\n",
350-
"- Dados sintéticos carregados? ✅\n",
351-
"- Layout 2x3 + sidebar? ✅\n",
352-
"- Gráficos e filtros dinâmicos? ✅\n",
353-
"- Crossfiltering funcionando? ✅\n",
354-
"- Acessibilidade e responsividade? ✅\n",
355-
"- Pronto para exportação/deploy? ✅\n",
356-
"\n",
357-
"**Para exportação HTML:** \n",
358-
"Após rodar o app, use a função de \"Salvar como página\" do navegador ou consulte [Deploying Dash Apps](https://dash.plotly.com/deployment) para deploy profissional."
359-
]
360-
},
361-
{
362-
"cell_type": "code",
363-
"metadata": {},
364-
"source": [
365-
"# Para Colab/Jupyter. Exibir o dashboard integrado abaixo:\n",
366-
"app.run_server(mode='inline', debug=False, port=8050)\n",
367-
"# Se estiver rodando em Codespace ou localmente, troque para:\n",
368-
"# app.run_server(debug=True, port=8050) # E acesse http://localhost:8050"
369-
]
370-
}
371-
],
372-
"metadata": {
373-
"colab": {
374-
"name": "Professional_Dashboard_Plotly.ipynb",
375-
"provenance": []
376-
},
377-
"kernelspec": {
378-
"display_name": "Python 3",
379-
"language": "python",
380-
"name": "python3"
381-
},
382-
"language_info": {
383-
"name": "python"
384-
}
385-
},
386-
"nbformat": 4,
387-
"nbformat_minor": 2
388-
}
1+
{"cells":[{"cell_type":"markdown","metadata":{},"source":["# Dashboard Profissional Python/Plotly — Implementação Completa\n","\n","Este notebook implementa, passo a passo, um dashboard interativo com múltiplos gráficos e filtros, seguindo as melhores práticas do repositório [Python-Data-Plotly-Predictive-Analytics-Dashbo[...]\n","\n","**Referências cruzadas:**\n","- `README.md` (estrutura e narrativa)\n","- `Knowledge-Base/03_Technical_Documentation/Official_Plotly_Dash_Docs/`\n","- `Professional Practices and Tips`\n","- `scripts/viz_new.py`\n","- `prompt_modelo.md` e `business_prompt.md` (storytelling)\n","- `requirements_processing.txt` (dependências)\n","- `DASHBOARD_EXECUTION_SUCCESS_REPORT.md` e `FINAL_STATUS_CHECK.md` (validação)\n","\n","**Execução:** \n","1. Instale as dependências indicadas.\n","2. Execute cada célula sequencialmente.\n","3. O dashboard estará disponível na saída ao final do notebook (Colab) ou em [http://localhost:8050](http://localhost:8050) (Codespace/Jupyter)." ]},{"cell_type":"markdown","metadata":{},"source":["---\n","# 1️⃣ PASSO 1: Setup de Ambiente e Importação de Bibliotecas\n","\n","Siga este passo tanto em Colab quanto Codespace para garantir o ambiente correto. Execute a célula abaixo **apenas uma vez** para instalar as dependências."]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Instale os pacotes necessários (descomente se necessário)\n","# Colab já inclui grande parte, mas garanta as versões certas:\n","!pip install -q dash==2.14.2 dash-bootstrap-components plotly pandas numpy jupyter-dash\n","import warnings\n","warnings.filterwarnings('ignore')"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Importação das bibliotecas principais\n","import pandas as pd\n","import numpy as np\n","import plotly.graph_objects as go\n","import plotly.express as px\n","from dash import dcc, html, Input, Output, State, callback_context\n","import dash_bootstrap_components as dbc\n","from dash.exceptions import PreventUpdate\n","\n","try:\n"," from jupyter_dash import JupyterDash\n","except ImportError:\n"," !pip install jupyter-dash\n"," from jupyter_dash import JupyterDash\n","\n","print(\"✅ Bibliotecas importadas com sucesso!\")"]}],"metadata":{"colab":{"name":"Professional_Dashboard_Plotly.ipynb","provenance":[]},"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":2}

0 commit comments

Comments
 (0)