在 plotly Dash 中显示一个简单的 matplotlib 图

Gio*_*oni 9 python matplotlib plotly plotly-dash

是否可以plt.show()在 plotly 的 Dash 框架中显示一个简单的 matplotlib 图(通常由 生成的那种)?或者只是带有 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)
Run Code Online (Sandbox Code Playgroud)

小智 9

请参阅https://plot.ly/matplotlib/modifying-a-matplotlib-figure/。库中有一个mpl_to_plotly函数plotly.tools可以从 matplotlib 图形返回一个绘图图形(然后可以返回到 Graph 的图形属性)。

编辑:刚注意到你不久前问过这个问题。也许以上是一个新功能,但它是最干净的方式。

  • 此功能已被视为已弃用,请参阅 https://github.com/plotly/plotly.py/issues/1568 (8认同)
  • 上面的链接遇到了 404 错误。还有其他选择吗? (4认同)

sim*_*PTA 5

如果您不想要交互式绘图,则可以返回静态绘图(从此帮助中找到)

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
    return "data:image/png;base64,{}".format(data)
Run Code Online (Sandbox Code Playgroud)