You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在Plotly Dash框架中展示Matplotlib生成的简易绘图?

在Dash中展示Matplotlib绘图的方法

当然可以在Dash框架里展示Matplotlib生成的简易绘图,完全不用局限于Plotly自带的Scatter、Bar这类trace组件!下面给你两种实用的实现方式:

方法1:将Matplotlib图转换为Plotly对象

Plotly提供了工具可以直接把Matplotlib的figure转换成Plotly兼容的figure,这样就能直接用dcc.Graph组件展示,步骤很简单:

  1. 导入plotly.tools里的mpl_to_plotly函数
  2. 用Matplotlib创建绘图并获取figure对象
  3. 转换为Plotly figure后,在回调里返回给dcc.Graph

示例代码:

import dash
from dash import dcc, html, Input, Output
import numpy as np
import matplotlib.pyplot as plt
from plotly.tools import mpl_to_plotly

app = dash.Dash(__name__)

app.layout = html.Div([
    html.H1("用Dash展示Matplotlib绘图"),
    dcc.Graph(id='mpl-graph'),
    dcc.Slider(
        id='slider',
        min=1,
        max=10,
        value=5,
        marks={i: str(i) for i in range(1, 11)}
    )
])

@app.callback(
    Output('mpl-graph', 'figure'),
    Input('slider', 'value')
)
def update_figure(slider_value):
    # 创建Matplotlib绘图
    fig, ax = plt.subplots()
    x = np.linspace(0, 10, 100)
    y = np.sin(x * slider_value)
    ax.plot(x, y, label=f'sin({slider_value}x)')
    ax.set_title('Matplotlib转Plotly示例')
    ax.legend()
    
    # 转换为Plotly figure
    plotly_fig = mpl_to_plotly(fig)
    plt.close(fig)  # 关闭Matplotlib的figure,避免内存泄漏
    return plotly_fig

if __name__ == '__main__':
    app.run_server(debug=True)

方法2:将Matplotlib图转为图片嵌入Dash

如果不需要交互式的Plotly功能,只是想展示静态的Matplotlib图,可以把图保存为内存中的图片,转成base64编码后用html.Img组件展示:

示例代码:

import dash
from dash import html, Input, Output
import numpy as np
import matplotlib.pyplot as plt
from io import BytesIO
import base64

app = dash.Dash(__name__)

app.layout = html.Div([
    html.H1("Matplotlib静态图嵌入Dash"),
    html.Img(id='mpl-image'),
    dcc.Slider(
        id='slider',
        min=1,
        max=10,
        value=5,
        marks={i: str(i) for i in range(1, 11)}
    )
])

@app.callback(
    Output('mpl-image', 'src'),
    Input('slider', 'value')
)
def update_image(slider_value):
    # 创建Matplotlib绘图
    fig, ax = plt.subplots()
    x = np.linspace(0, 10, 100)
    y = np.cos(x * slider_value)
    ax.plot(x, y, color='red', label=f'cos({slider_value}x)')
    ax.set_title('静态Matplotlib图示例')
    ax.legend()
    
    # 将图保存到内存BytesIO
    buf = BytesIO()
    fig.savefig(buf, format='png')
    buf.seek(0)
    # 转成base64编码
    img_base64 = base64.b64encode(buf.getvalue()).decode('utf-8')
    plt.close(fig)  # 关闭figure释放资源
    return f'data:image/png;base64,{img_base64}'

if __name__ == '__main__':
    app.run_server(debug=True)

注意事项

  • 每次创建Matplotlib figure后一定要调用plt.close(fig),避免内存泄漏——毕竟Dash的回调会频繁触发,不关闭的话内存会持续占用
  • 第一种方法转换后的Plotly图会尽量保留Matplotlib的样式,但有些复杂的Matplotlib特性可能无法完美转换,如果遇到样式问题,可以试试调整Matplotlib的绘图参数,或者直接用Plotly原生trace实现
  • 第二种方法生成的是静态图,没有Plotly那种交互式功能(比如缩放、悬停查看数据点),适合只需要展示静态结果的场景

内容的提问来源于stack exchange,提问作者Giora Simchoni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:05:43