# Q1 = df['error_forecast_fact'].quantile(0.25)
# Q3 = df['error_forecast_fact'].quantile(0.75)
# IQR = Q3 - Q1
df_no_outliers = df[
(df['error_forecast_fact'] >= df['error_forecast_fact'].quantile(0.01)) &
(df['error_forecast_fact'] <= df['error_forecast_fact'].quantile(0.99))
]
fig = make_subplots(rows=1, cols=2, subplot_titles=("С выбросами", "Без выбросов"), shared_yaxes=True)
colors = ['red', 'green', 'blue', 'orange', 'grey']
overall_color = 'black'
seller_types = df['seller_type'].unique()
fig.add_trace(go.Histogram(x=df['error_forecast_fact'], name="Все продавцы (все)", marker_color=overall_color,
opacity=0.4, nbinsx=100), row=1, col=1)
for i, seller in enumerate(seller_types):
fig.add_trace(go.Histogram(x=df[df['seller_type'] == seller]['error_forecast_fact'],
name=f"{seller} (все)", marker_color=colors[i % len(colors)],
opacity=0.6, nbinsx=100), row=1, col=1)
fig.add_trace(go.Histogram(x=df_no_outliers['error_forecast_fact'], name="Все продавцы (без выбросов)",
marker_color=overall_color, opacity=0.4, nbinsx=100), row=1, col=2)
for i, seller in enumerate(seller_types):
fig.add_trace(go.Histogram(x=df_no_outliers[df_no_outliers['seller_type'] == seller]['error_forecast_fact'],
name=f"{seller} (без выбросов)", marker_color=colors[i % len(colors)],
opacity=0.6, nbinsx=100), row=1, col=2)
# fig.update_layout(
# title_text="Распределение ошибок прогноза по типу продавца",
# xaxis_title="Ошибка прогноза (forecast - fact)",
# yaxis_title="Количество наблюдений",
# # bargap=0.1,
# barmode='overlay',
# width=1100,
# height=500
# )
task.logger.report_plotly(title="Ошибка прогноза (forecast - fact)",
series="error_histograms_with_total", iteration=0, figure=fig)
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
import numpy as np
# Пример данных
np.random.seed(42)
data = {
'forecast_gmv': np.random.rand(100) * 100,
'sum_gmv': np.random.rand(100) * 100,
'seller_type': np.random.choice(['Type1', 'Type2', 'Type3'], 100)
}
ffill_res_long_df = pd.DataFrame(data)
def plot_error_distribution(ffill_res_long_df, task):
df = ffill_res_long_df.copy()
df['error_forecast_fact'] = df['forecast_gmv'] - df['sum_gmv']
df_no_outliers = df[
(df['error_forecast_fact'] >= df['error_forecast_fact'].quantile(0.01)) &
(df['error_forecast_fact'] <= df['error_forecast_fact'].quantile(0.99))
]
fig = make_subplots(rows=1, cols=2, subplot_titles=("С выбросами", "Без выбросов"), shared_yaxes=True)
colors = ['red', 'green', 'blue', 'orange', 'grey']
overall_color = 'black'
seller_types = df['seller_type'].unique()
# Функция для обновления графиков
def update_graph(seller_type):
fig.data = [] # Очищаем предыдущие данные
fig.add_trace(go.Histogram(x=df['error_forecast_fact'], name="Все продавцы (все)", marker_color=overall_color,
opacity=0.4, nbinsx=100), row=1, col=1)
if seller_type == 'Все':
for i, seller in enumerate(seller_types):
fig.add_trace(go.Histogram(x=df[df['seller_type'] == seller]['error_forecast_fact'],
name=f"{seller} (все)", marker_color=colors[i % len(colors)],
opacity=0.6, nbinsx=100), row=1, col=1)
else:
fig.add_trace(go.Histogram(x=df[df['seller_type'] == seller_type]['error_forecast_fact'],
name=f"{seller_type} (все)", marker_color=colors[seller_types.tolist().index(seller_type) % len(colors)],
opacity=0.6, nbinsx=100), row=1, col=1)
fig.add_trace(go.Histogram(x=df_no_outliers['error_forecast_fact'], name="Все продавцы (без выбросов)",
marker_color=overall_color, opacity=0.4, nbinsx=100), row=1, col=2)
if seller_type == 'Все':
for i, seller in enumerate(seller_types):
fig.add_trace(go.Histogram(x=df_no_outliers[df_no_outliers['seller_type'] == seller]['error_forecast_fact'],
name=f"{seller} (без выбросов)", marker_color=colors[i % len(colors)],
opacity=0.6, nbinsx=100), row=1, col=2)
else:
fig.add_trace(go.Histogram(x=df_no_outliers[df_no_outliers['seller_type'] == seller_type]['error_forecast_fact'],
name=f"{seller_type} (без выбросов)", marker_color=colors[seller_types.tolist().index(seller_type) % len(colors)],
opacity=0.6, nbinsx=100), row=1, col=2)
# Добавляем dropdown для выбора типа продавца
seller_type_options = [{'label': 'Все', 'method': 'restyle', 'args': [{}]}] + \
[{'label': seller, 'method': 'restyle', 'args': [{}]} for seller in seller_types]
fig.update_layout(
updatemenus=[
dict(
active=0,
buttons=list([
dict(
args=[{"frames": [{"name": "all", "data": fig.data}]}],
label="Все",
method="update"
),
*[
dict(
args=[{"frames": [{"name": seller, "data": [trace for trace in fig.data if trace.name.startswith(seller)]}]}],
label=seller,
method="update"
) for seller in seller_types
]
]),
direction="down",
pad={"r": 10, "t": 10},
showactive=True,
x=0.1,
xanchor="left",
y=1.15,
yanchor="top"
),
],
title_text="Распределение ошибок прогноза по типу продавца",
xaxis_title="Ошибка прогноза (forecast - fact)",
yaxis_title="Количество наблюдений",
barmode='overlay',
width=1100,
height=500
)
# Инициализация графика с "Все" типами продавцов
update_graph('Все')
task.logger.report_plotly(title="Ошибка прогноза (forecast - fact)",
series="error_histograms_with_total", iteration=0, figure=fig)
# Пример вызова функции
# plot_error_distribution(ffill_res_long_df, task)