Spaces:
Build error
Build error
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +276 -38
src/streamlit_app.py
CHANGED
|
@@ -1,40 +1,278 @@
|
|
| 1 |
-
import altair as alt
|
| 2 |
-
import numpy as np
|
| 3 |
-
import pandas as pd
|
| 4 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
|
| 10 |
-
If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
|
| 11 |
-
forums](https://discuss.streamlit.io).
|
| 12 |
-
|
| 13 |
-
In the meantime, below is an example of what you can do with just a few lines of code:
|
| 14 |
-
"""
|
| 15 |
-
|
| 16 |
-
num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
|
| 17 |
-
num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
|
| 18 |
-
|
| 19 |
-
indices = np.linspace(0, 1, num_points)
|
| 20 |
-
theta = 2 * np.pi * num_turns * indices
|
| 21 |
-
radius = indices
|
| 22 |
-
|
| 23 |
-
x = radius * np.cos(theta)
|
| 24 |
-
y = radius * np.sin(theta)
|
| 25 |
-
|
| 26 |
-
df = pd.DataFrame({
|
| 27 |
-
"x": x,
|
| 28 |
-
"y": y,
|
| 29 |
-
"idx": indices,
|
| 30 |
-
"rand": np.random.randn(num_points),
|
| 31 |
-
})
|
| 32 |
-
|
| 33 |
-
st.altair_chart(alt.Chart(df, height=700, width=700)
|
| 34 |
-
.mark_point(filled=True)
|
| 35 |
-
.encode(
|
| 36 |
-
x=alt.X("x", axis=None),
|
| 37 |
-
y=alt.Y("y", axis=None),
|
| 38 |
-
color=alt.Color("idx", legend=None, scale=alt.Scale()),
|
| 39 |
-
size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
|
| 40 |
-
))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import plotly.express as px
|
| 5 |
+
import plotly.graph_objects as go
|
| 6 |
+
|
| 7 |
+
# --- Configuração da Página ---
|
| 8 |
+
st.set_page_config(layout="wide", page_title="Dashboard de Reciclagem v0 Estruturado")
|
| 9 |
+
|
| 10 |
+
# --- Dados (Originais do v0) ---
|
| 11 |
+
meses = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez']
|
| 12 |
+
dados_2024 = {
|
| 13 |
+
'Mes': meses,
|
| 14 |
+
'Papel_Papelao': [8047, 11287, 8184, 10183, 5699, 5830, 7465, 5600, 2960, 5175, 9656, 3960],
|
| 15 |
+
'Plastico': [6353, 8771, 6993, 8050, 4880, 5296, 5937, 4747, 2446, 4109, 7667, 3367],
|
| 16 |
+
'Metal': [1061, 2025, 1121, 1832, 716, 936, 1553, 904, 361, 630, 1904, 569],
|
| 17 |
+
'Vidro': [5248, 6929, 6014, 5821, 3697, 3655, 4950, 3360, 1580, 3261, 6173, 2357]
|
| 18 |
+
}
|
| 19 |
+
df_2024 = pd.DataFrame(dados_2024)
|
| 20 |
+
|
| 21 |
+
dados_anuais = {
|
| 22 |
+
'Ano': [2022, 2023, 2024],
|
| 23 |
+
'Papel_Papelao': [18780, 58718, 84046],
|
| 24 |
+
'Plastico': [5340, 1041, 8279],
|
| 25 |
+
'Metal': [1300, 1737, 19955],
|
| 26 |
+
'Vidro': [0, 725, 1709]
|
| 27 |
+
}
|
| 28 |
+
df_anuais = pd.DataFrame(dados_anuais)
|
| 29 |
+
|
| 30 |
+
precos = {
|
| 31 |
+
'Papel_Papelao': 0.50,
|
| 32 |
+
'Plastico': 0.80,
|
| 33 |
+
'Metal': 2.00,
|
| 34 |
+
'Vidro': 0.30
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
# --- Estatísticas descritivas (Originais do v0) ---
|
| 38 |
+
df_2024_numeric = df_2024.drop(columns='Mes')
|
| 39 |
+
desc = df_2024_numeric.describe().T
|
| 40 |
+
desc['Mediana'] = df_2024_numeric.median()
|
| 41 |
+
desc = desc[['mean', 'Mediana', 'std', 'min', 'max']]
|
| 42 |
+
desc.columns = ['Média', 'Mediana', 'Desvio Padrão', 'Mínimo', 'Máximo']
|
| 43 |
+
|
| 44 |
+
# --- Simulação de faturamento (Originais do v0) ---
|
| 45 |
+
estatisticas_simulacao = {} # Renomeado para evitar conflito com o df 'estatisticas' se existir
|
| 46 |
+
for material_key in precos.keys(): # Evitar conflito com a variável 'material' do selectbox
|
| 47 |
+
media = df_2024_numeric[material_key].mean()
|
| 48 |
+
std = df_2024_numeric[material_key].std()
|
| 49 |
+
estatisticas_simulacao[material_key] = {'media': media, 'std': std}
|
| 50 |
+
|
| 51 |
+
def simular_faturamento_anual(estats, precos_dict, fator=1.0, n_sim=1000, seed=42):
|
| 52 |
+
np.random.seed(seed)
|
| 53 |
+
faturamentos = []
|
| 54 |
+
for _ in range(n_sim):
|
| 55 |
+
total = 0
|
| 56 |
+
for mat_sim, stats_sim in estats.items():
|
| 57 |
+
medias = stats_sim['media'] * fator
|
| 58 |
+
stds = stats_sim['std']
|
| 59 |
+
# Garantir que o desvio padrão não seja negativo ou zero se a média for zero
|
| 60 |
+
quantidades = np.random.normal(medias, stds if stds > 0 else 1e-6, 12)
|
| 61 |
+
quantidades = np.clip(quantidades, 0, None) # Quantidades não podem ser negativas
|
| 62 |
+
total += quantidades.sum() * precos_dict[mat_sim]
|
| 63 |
+
faturamentos.append(total)
|
| 64 |
+
return np.array(faturamentos)
|
| 65 |
+
|
| 66 |
+
cenarios_simulacao = { # Renomeado para evitar conflito
|
| 67 |
+
'Base': 1.0,
|
| 68 |
+
'Otimista': 1.15,
|
| 69 |
+
'Pessimista': 0.85
|
| 70 |
+
}
|
| 71 |
+
# Cores para os gráficos de cenário
|
| 72 |
+
cores_graf_cenarios = {'Base': '#1f77b4', 'Otimista': '#2ca02c', 'Pessimista': '#d62728'}
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
# --- Interface Streamlit ---
|
| 76 |
+
st.sidebar.title("🔩 Configurações e Navegação")
|
| 77 |
+
secao_analise = st.sidebar.radio(
|
| 78 |
+
"Selecione a Seção de Análise:",
|
| 79 |
+
("Visão Geral da Coleta", "Análise Estatística da Coleta", "Simulação de Faturamento"),
|
| 80 |
+
captions = ["Tendências anuais e mensais", "Descritivas e distribuições", "Projeções e cenários"]
|
| 81 |
+
)
|
| 82 |
+
st.sidebar.markdown("---")
|
| 83 |
+
|
| 84 |
+
# Filtros (relevância depende da seção)
|
| 85 |
+
st.sidebar.subheader("Filtros Gerais")
|
| 86 |
+
materiais_opcoes = ['Todos'] + list(precos.keys())
|
| 87 |
+
material_filtro = st.sidebar.selectbox('Selecione o material:', materiais_opcoes)
|
| 88 |
+
|
| 89 |
+
# O filtro de cenário só é relevante para a seção de faturamento
|
| 90 |
+
cenario_filtro = 'Todos' # Default
|
| 91 |
+
if secao_analise == "Simulação de Faturamento":
|
| 92 |
+
cenarios_opcoes_filtro = ['Todos'] + list(cenarios_simulacao.keys())
|
| 93 |
+
cenario_filtro = st.sidebar.selectbox('Selecione o cenário de faturamento:', cenarios_opcoes_filtro)
|
| 94 |
+
|
| 95 |
+
st.sidebar.markdown("---")
|
| 96 |
+
st.sidebar.info(f"Dashboard de Reciclagem (v0 Estruturado)\nDados de 2022-2024. Simulações baseadas em 2024.\nAtualizado em: {pd.Timestamp('now').strftime('%d/%m/%Y')}")
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
# --- Conteúdo Principal ---
|
| 100 |
+
st.title('♻️ Dashboard de Recicláveis e Faturamento')
|
| 101 |
+
st.markdown(f"### Seção Atual: {secao_analise}")
|
| 102 |
+
st.markdown("---")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
if secao_analise == "Visão Geral da Coleta":
|
| 106 |
+
st.header("📈 Evolução da Coleta de Materiais")
|
| 107 |
+
st.caption(f"Visualizando dados para: {material_filtro}")
|
| 108 |
+
|
| 109 |
+
tab_anual, tab_mensal = st.tabs(["Evolução Anual", "Evolução Mensal (2024)"])
|
| 110 |
+
|
| 111 |
+
with tab_anual:
|
| 112 |
+
if material_filtro != 'Todos':
|
| 113 |
+
st.subheader(f'Evolução Anual de {material_filtro}')
|
| 114 |
+
if material_filtro in df_anuais.columns:
|
| 115 |
+
fig_anual = px.bar(df_anuais, x=df_anuais.index, y=material_filtro,
|
| 116 |
+
title=f'Coleta Anual de {material_filtro}',
|
| 117 |
+
labels={'value': 'Quantidade (kg)', 'Ano': 'Ano', material_filtro: 'Quantidade (kg)'},
|
| 118 |
+
template='plotly_white', text_auto='.2s')
|
| 119 |
+
fig_anual.update_layout(xaxis_title='Ano', yaxis_title='Quantidade (kg)')
|
| 120 |
+
st.plotly_chart(fig_anual, use_container_width=True)
|
| 121 |
+
else:
|
| 122 |
+
st.warning(f"Dados anuais não disponíveis para '{material_filtro}'.")
|
| 123 |
+
else:
|
| 124 |
+
st.subheader('Evolução Anual de Todos os Materiais')
|
| 125 |
+
df_anuais_melt = df_anuais.reset_index().melt(id_vars='Ano', var_name='Material', value_name='Quantidade')
|
| 126 |
+
fig_anual_todos = px.bar(df_anuais_melt, x='Ano', y='Quantidade', color='Material', barmode='group',
|
| 127 |
+
title='Coleta Anual de Todos os Materiais',
|
| 128 |
+
labels={'Quantidade': 'Quantidade (kg)', 'Ano': 'Ano'},
|
| 129 |
+
template='plotly_white', text_auto='.2s')
|
| 130 |
+
fig_anual_todos.update_layout(xaxis_title='Ano', yaxis_title='Quantidade (kg)')
|
| 131 |
+
st.plotly_chart(fig_anual_todos, use_container_width=True)
|
| 132 |
+
|
| 133 |
+
with tab_mensal:
|
| 134 |
+
if material_filtro != 'Todos':
|
| 135 |
+
st.subheader(f'Evolução Mensal de {material_filtro} em 2024')
|
| 136 |
+
if material_filtro in df_2024.columns: # df_2024 agora tem 'Mes' como index
|
| 137 |
+
fig_mensal = px.line(df_2024, x=df_2024.index, y=material_filtro, markers=True,
|
| 138 |
+
title=f'Coleta Mensal de {material_filtro} (2024)',
|
| 139 |
+
labels={'index': 'Mês', material_filtro: 'Quantidade (kg)'}, template='plotly_white')
|
| 140 |
+
fig_mensal.update_layout(xaxis_title='Mês', yaxis_title='Quantidade (kg)')
|
| 141 |
+
st.plotly_chart(fig_mensal, use_container_width=True)
|
| 142 |
+
else:
|
| 143 |
+
st.warning(f"Dados mensais de 2024 não disponíveis para '{material_filtro}'.")
|
| 144 |
+
else:
|
| 145 |
+
st.subheader('Evolução Mensal de Todos os Materiais em 2024')
|
| 146 |
+
df_2024_melt = df_2024_numeric.reset_index().melt(id_vars='Mes', var_name='Material', value_name='Quantidade')
|
| 147 |
+
fig_mensal_todos = px.line(df_2024_melt, x='Mes', y='Quantidade', color='Material', markers=True,
|
| 148 |
+
title='Coleta Mensal de Todos os Materiais (2024)',
|
| 149 |
+
labels={'Mes': 'Mês', 'Quantidade': 'Quantidade (kg)'}, template='plotly_white')
|
| 150 |
+
fig_mensal_todos.update_layout(xaxis_title='Mês', yaxis_title='Quantidade (kg)')
|
| 151 |
+
st.plotly_chart(fig_mensal_todos, use_container_width=True)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
elif secao_analise == "Análise Estatística da Coleta":
|
| 155 |
+
st.header("📊 Análise Estatística da Coleta (Baseado em Dados Mensais de 2024)")
|
| 156 |
+
|
| 157 |
+
tab_desc, tab_box = st.tabs(["Estatísticas Descritivas", "Boxplot dos Materiais"])
|
| 158 |
+
|
| 159 |
+
with tab_desc:
|
| 160 |
+
st.subheader('Tabela de Estatísticas Descritivas')
|
| 161 |
+
st.caption("Quantidades médias, medianas, desvios, mínimos e máximos mensais por material em 2024.")
|
| 162 |
+
st.dataframe(desc.style.format('{:,.2f}'), use_container_width=True)
|
| 163 |
+
|
| 164 |
+
with tab_box:
|
| 165 |
+
st.subheader('Distribuição das Quantidades Mensais por Material (Boxplot)')
|
| 166 |
+
st.caption(f"Visualizando para: {material_filtro}")
|
| 167 |
+
df_melt_box = df_2024_numeric.reset_index().melt(id_vars='Mes', var_name='Material', value_name='Quantidade')
|
| 168 |
+
|
| 169 |
+
if material_filtro != 'Todos':
|
| 170 |
+
df_melt_box_filtrado = df_melt_box[df_melt_box['Material'] == material_filtro]
|
| 171 |
+
else:
|
| 172 |
+
df_melt_box_filtrado = df_melt_box
|
| 173 |
+
|
| 174 |
+
if not df_melt_box_filtrado.empty:
|
| 175 |
+
fig_boxplot = px.box(df_melt_box_filtrado, x='Material', y='Quantidade',
|
| 176 |
+
color='Material' if material_filtro == 'Todos' else None,
|
| 177 |
+
title='Distribuição das Quantidades Mensais (2024)',
|
| 178 |
+
labels={'Quantidade': 'Quantidade (kg)'}, template='plotly_white')
|
| 179 |
+
fig_boxplot.update_layout(xaxis_title='Material', yaxis_title='Quantidade (kg)')
|
| 180 |
+
st.plotly_chart(fig_boxplot, use_container_width=True)
|
| 181 |
+
else:
|
| 182 |
+
st.warning(f"Não há dados para exibir no boxplot para '{material_filtro}'.")
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
elif secao_analise == "Simulação de Faturamento":
|
| 186 |
+
st.header("💰 Simulação de Faturamento Anual")
|
| 187 |
+
st.caption(f"Analisando Material: {material_filtro}, Cenário: {cenario_filtro}")
|
| 188 |
+
|
| 189 |
+
# Funções de plotagem e tabela de resumo da simulação (originais do v0, adaptadas)
|
| 190 |
+
def criar_tabela_resumo_simulacao(simulacoes_dict):
|
| 191 |
+
dados = []
|
| 192 |
+
# Iterar sobre as chaves dos cenários de simulação para manter a ordem
|
| 193 |
+
for nome_cenario_sim in cenarios_simulacao.keys():
|
| 194 |
+
if nome_cenario_sim in simulacoes_dict:
|
| 195 |
+
media_val = simulacoes_dict[nome_cenario_sim].mean()
|
| 196 |
+
std_val = simulacoes_dict[nome_cenario_sim].std()
|
| 197 |
+
dados.append([nome_cenario_sim, f"R$ {media_val:,.2f}", f"R$ {std_val:,.2f}"])
|
| 198 |
+
df_res = pd.DataFrame(dados, columns=['Cenário', 'Faturamento Anual Médio', 'Desvio Padrão'])
|
| 199 |
+
return df_res.set_index('Cenário')
|
| 200 |
+
|
| 201 |
+
def criar_grafico_cenarios_simulacao(simulacoes_dict, titulo_grafico):
|
| 202 |
+
fig = go.Figure()
|
| 203 |
+
# Iterar sobre as chaves dos cenários de simulação para manter a ordem e cores
|
| 204 |
+
for nome_cenario_sim in cenarios_simulacao.keys():
|
| 205 |
+
if nome_cenario_sim in simulacoes_dict:
|
| 206 |
+
fig.add_trace(go.Histogram(
|
| 207 |
+
x=simulacoes_dict[nome_cenario_sim],
|
| 208 |
+
name=nome_cenario_sim,
|
| 209 |
+
histnorm='probability density',
|
| 210 |
+
opacity=0.6,
|
| 211 |
+
nbinsx=40, # Ajustado para melhor visualização
|
| 212 |
+
marker_color=cores_graf_cenarios[nome_cenario_sim],
|
| 213 |
+
showlegend=True
|
| 214 |
+
))
|
| 215 |
+
media_val = simulacoes_dict[nome_cenario_sim].mean()
|
| 216 |
+
fig.add_vline(x=media_val, line_dash='dash', line_color=cores_graf_cenarios[nome_cenario_sim],
|
| 217 |
+
annotation_text=f'Média {nome_cenario_sim}: R${media_val:,.0f}',
|
| 218 |
+
annotation_position='top right' if nome_cenario_sim != 'Pessimista' else 'top left',
|
| 219 |
+
annotation_font_size=10)
|
| 220 |
+
fig.update_layout(
|
| 221 |
+
barmode='overlay',
|
| 222 |
+
title_text=titulo_grafico,
|
| 223 |
+
xaxis_title_text='Faturamento Total Anual (R$)',
|
| 224 |
+
yaxis_title_text='Densidade de Probabilidade',
|
| 225 |
+
legend_title_text='Cenário',
|
| 226 |
+
template='plotly_white',
|
| 227 |
+
title_font_size=16
|
| 228 |
+
)
|
| 229 |
+
return fig
|
| 230 |
+
|
| 231 |
+
# Lógica de simulação e exibição (adaptada do v0)
|
| 232 |
+
if material_filtro != 'Todos':
|
| 233 |
+
estats_filtradas = {material_filtro: estatisticas_simulacao[material_filtro]}
|
| 234 |
+
precos_filtrados = {material_filtro: precos[material_filtro]}
|
| 235 |
+
titulo_base_grafico = f"Simulação para {material_filtro}"
|
| 236 |
+
else:
|
| 237 |
+
estats_filtradas = estatisticas_simulacao
|
| 238 |
+
precos_filtrados = precos
|
| 239 |
+
titulo_base_grafico = "Simulação para Todos os Materiais"
|
| 240 |
+
|
| 241 |
+
if cenario_filtro != 'Todos':
|
| 242 |
+
# Simulação para um cenário específico
|
| 243 |
+
fator_unico = cenarios_simulacao[cenario_filtro]
|
| 244 |
+
dados_simulados_unicos = simular_faturamento_anual(estats_filtradas, precos_filtrados, fator=fator_unico)
|
| 245 |
+
|
| 246 |
+
st.subheader(f"Distribuição para Cenário: {cenario_filtro} ({titulo_base_grafico.split('para ')[1]})")
|
| 247 |
+
fig_sim_unica = px.histogram(dados_simulados_unicos, nbins=50, histnorm='probability density',
|
| 248 |
+
title=f'Faturamento Anual Simulado - {titulo_base_grafico} ({cenario_filtro})',
|
| 249 |
+
labels={'value': 'Faturamento Anual (R$)'}, template='plotly_white')
|
| 250 |
+
fig_sim_unica.update_traces(marker_color=cores_graf_cenarios.get(cenario_filtro, '#808080'))
|
| 251 |
+
media_sim_unica = dados_simulados_unicos.mean()
|
| 252 |
+
fig_sim_unica.add_vline(x=media_sim_unica, line_dash='dash', line_color='black',
|
| 253 |
+
annotation_text=f'Média: R$ {media_sim_unica:,.0f}', annotation_position='top right')
|
| 254 |
+
st.plotly_chart(fig_sim_unica, use_container_width=True)
|
| 255 |
+
st.write(f"**Faturamento Anual Médio Simulado:** R$ {media_sim_unica:,.2f}")
|
| 256 |
+
st.write(f"**Desvio Padrão:** R$ {dados_simulados_unicos.std():,.2f}")
|
| 257 |
+
|
| 258 |
+
else: # cenario_filtro == 'Todos'
|
| 259 |
+
# Simulações para todos os cenários (Base, Otimista, Pessimista)
|
| 260 |
+
simulacoes_completas = {
|
| 261 |
+
nome_cen: simular_faturamento_anual(estats_filtradas, precos_filtrados, fator=fator_cen)
|
| 262 |
+
for nome_cen, fator_cen in cenarios_simulacao.items()
|
| 263 |
+
}
|
| 264 |
+
st.subheader(f"Comparativo de Cenários ({titulo_base_grafico.split('para ')[1]})")
|
| 265 |
+
|
| 266 |
+
tab_graf_sim, tab_tab_sim = st.tabs(["Distribuição dos Cenários", "Resumo Estatístico"])
|
| 267 |
+
|
| 268 |
+
with tab_graf_sim:
|
| 269 |
+
fig_todos_cenarios = criar_grafico_cenarios_simulacao(simulacoes_completas,
|
| 270 |
+
f"Comparativo de Cenários de Faturamento ({titulo_base_grafico.split('para ')[1]})")
|
| 271 |
+
st.plotly_chart(fig_todos_cenarios, use_container_width=True)
|
| 272 |
+
|
| 273 |
+
with tab_tab_sim:
|
| 274 |
+
df_resumo_todos_cenarios = criar_tabela_resumo_simulacao(simulacoes_completas)
|
| 275 |
+
st.dataframe(df_resumo_todos_cenarios, use_container_width=True)
|
| 276 |
|
| 277 |
+
else:
|
| 278 |
+
st.error("Seção de análise não reconhecida.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|