以plotly Dash显示简单的matplotlib图

slwdgvem  于 2022-12-23  发布在  其他
关注(0)|答案(3)|浏览(179)

是否可以在plotly的Dash框架中显示一个简单的matplotlib图(通常由plt.show()生成的那种)?或者只是带有plotly的散点图和数据迹线的类似于plotly的图形?
具体来说,我想我需要一个不同于Graph的组件(见下文),以及一种在update_figure函数中返回简单绘图的方法。
示例:

import dash
import dash_core_components as dcc
import dash_html_components as html
import numpy as np
import matplotlib.pyplot as plt

app = dash.Dash()

app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),

    dcc.Slider(
        id='n_points',
        min=10,
        max=100,
        step=1,
        value=50,
    ),

    dcc.Graph(id='example') # or something other than Graph?...
])

@app.callback(
    dash.dependencies.Output('example', 'figure'),
    [dash.dependencies.Input('n_points', 'value')]
)

def update_figure(n_points):
    #create some matplotlib graph
    x = np.random.rand(n_points)
    y = np.random.rand(n_points)
    plt.scatter(x, y)
    # plt.show()
    return None # return what, I don't know exactly, `plt`?

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

6uxekuva1#

参见https://plot.ly/matplotlib/modifying-a-matplotlib-figure/plotly.tools库中有一个mpl_to_plotly函数,该函数会从matplotlib图形中返回一个plotly图形(可以返回Graph的图形属性)。
编辑:刚刚注意到你问了这个问题。也许上面是一个新功能,但它是最干净的方式。

sbtkgmzw

sbtkgmzw2#

如果不需要交互图,可以返回静态图(可从本帮助中找到)

import io
import base64

...
    
app.layout = html.Div(children=[
    ...,

    html.Img(id='example') # img element
])

@app.callback(
    dash.dependencies.Output('example', 'src'), # src attribute
    [dash.dependencies.Input('n_points', 'value')]
)
def update_figure(n_points):
    #create some matplotlib graph
    x = np.random.rand(n_points)
    y = np.random.rand(n_points)
    buf = io.BytesIO() # in-memory files
    plt.scatter(x, y)
    plt.savefig(buf, format = "png") # save to the above file object
    plt.close()
    data = base64.b64encode(buf.getbuffer()).decode("utf8") # encode to html elements
    buf.close()
    return "data:image/png;base64,{}".format(data)
r3i60tvu

r3i60tvu3#

UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail

在我的情况下,它的工作,尽管警告消息👍👍

相关问题