• Почему не получается сохранять графики plotly как картинки?

    @ToDaYka Автор вопроса
    def create_plot(data_before, data_after, time_column, Pokazatel, recommended_value, y_title, color_before, color_after, doc, caption, include_recommended_value=True):
        data_before[time_column] = pd.to_datetime(data_before[time_column])
        data_after[time_column] = pd.to_datetime(data_after[time_column])
    
        data_before = data_before.dropna(subset=[Pokazatel])
        data_after = data_after.dropna(subset=[Pokazatel])
    
        category_name = {
            'pH': 'Водородный показатель',
            'Suspended_solids': 'Взвешенные вещества',
            'Petroleum_products': 'Нефтепродукты',
            'Total_iron': 'Железо общее'
        }.get(Pokazatel, Pokazatel)
    
        min_value = min(data_before[Pokazatel].min(), data_after[Pokazatel].min())
        max_value = max(data_before[Pokazatel].max(), data_after[Pokazatel].max())
    
        y_lower = math.floor(min_value - 0.5) if min_value - 0.5 > 0 else 0
    
        data_range = max_value - min_value
        grid_step = math.ceil(data_range / 10)  
    
        y_upper = math.ceil(max(max_value, recommended_value) / grid_step) * grid_step + grid_step
    
        if recommended_value is None:
            recommended_value = 0  
    
        fig = go.Figure()
    
        last_selection_point_before = data_before['Selection_point'].iloc[-1]
    
        fig.add_trace(go.Scatter(
            x=data_before[time_column],
            y=data_before[Pokazatel],
            mode='lines+markers',
            name=f'До очистки ({last_selection_point_before})',
            line=dict(color=color_before, width=3),
            marker=dict(size=10)
        ))
    
        last_selection_point_after = data_after['Selection_point'].iloc[-1]
    
        fig.add_trace(go.Scatter(
            x=data_after[time_column],
            y=data_after[Pokazatel],
            mode='lines+markers',
            name=f'После очистки ({last_selection_point_after})',
            line=dict(color=color_after, width=3),
            marker=dict(size=10)
        ))
    
        if include_recommended_value:
            fig.add_shape(
                type="line",
                x0=start_date - pd.Timedelta(days=10),
                x1=end_date + pd.Timedelta(days=10),
                y0=recommended_value,
                y1=recommended_value,
                line=dict(color="red", width=3),
            )
            fig.add_trace(go.Scatter(
                x=[None], y=[None],
                mode='lines',
                line=dict(color='red', width=3),
                name='Рекомендуемое значение'
            ))
    
        fig.update_yaxes(tickformat=",.1f", title=y_title, range=[y_lower, y_upper])
        fig.update_xaxes(tickformat="%d.%m.%Y", tickangle=270, title=None)
        fig.update_layout(
            showlegend=True,
            legend=dict(
                title_text='',
                orientation="h",
                yanchor="bottom",
                y=1,
                xanchor="center",
                x=0.5
            ),
            margin=dict(l=0, r=0, t=0, b=0),
            font=dict(family="Times New Roman", size=16)
        )
    
        try:
            img_bytes = fig.to_image(format="png", width=700, height=450, scale=3)
        except Exception as e:
            print(f"Ошибка при создании изображения: {e}")
            return
    
        doc.add_picture(io.BytesIO(img_bytes), width=Inches(5.9), height=Inches(3.52))
        last_paragraph = doc.paragraphs[-1]
        last_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
        caption_paragraph = doc.add_paragraph(caption)
        caption_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
        caption_paragraph.style.font.name = 'Times New Roman'
        caption_paragraph.style.font.size = Pt(12)


    В строку конвертировал, но тогда весь макет графика сбивается.
    Написано