【问题标题】:Showing a simple matplotlib plot in plotly Dash在 plotly Dash 中显示一个简单的 matplotlib 图
【发布时间】:2018-04-16 07:00:50
【问题描述】:

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

【问题讨论】:

  • 想法:将matplotlib图作为普通图像处理,并将其设置为plotly图的背景图像

标签: python matplotlib plotly plotly-dash


【解决方案1】:

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

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

【讨论】:

【解决方案2】:

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

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)

【讨论】:

    【解决方案3】:
    UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail
    

    在我的情况下它可以工作,尽管有警告信息 ??

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-25
      • 2022-07-30
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      • 2021-11-04
      相关资源
      最近更新 更多