【问题标题】:plotly dash - generate image with plotly, safe it local and display it with plotly dashplotly dash - 使用 plotly 生成图像,将其保存在本地并使用 plotly dash 显示
【发布时间】:2021-08-02 18:00:14
【问题描述】:

我用 plotly (express) 生成了很多图像,并将它们作为 png 保存在本地目录中。现在我想用 plotly dash 创建一个仪表板。我生成的图像有很多依赖关系,这就是我不想将代码包含到dash应用程序代码中的原因。

现在我问,是否可以将图像以格式(HTML?)保存在我的本地目录中并通过 plotly dash 调用它们?!

我的问题是,我必须如何保存图像,以及如何调用它?我不想使用 PNG(等),因为我想使用悬停功能

这是我尝试过的:

import plotly.express as px

fig =px.scatter(x=range(10), y=range(10))
fig.write_html("../example_codes/saved_as_HTML.html")
#%%

import dash
import dash_html_components as html
import base64

app = dash.Dash()

image_filename = 'saved_as_HTML.html' # replace with your own image
encoded_image = base64.b64encode(open(image_filename, 'rb').read())

# app.layout = html.Div([
#     html.Img(src='data:image/png;base64,{}'.format(encoded_image))
# ])


app.layout = html.Div([
    html.Img(src='data:image/html;base64,{}'.format(encoded_image))
])

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

【问题讨论】:

    标签: python plotly dashboard plotly-dash


    【解决方案1】:

    我会以不同的方式解决问题。

    我不会使用 html 作为格式,而是使用 joblib 保存和加载 Python 图,因为这些图只是普通的 Python 对象。

    # Save the figures somewhere
    import joblib
    fig = px.scatter(x=range(10), y=range(10))
    joblib.dump(fig, "../example_codes/fig.pkl")
    

    将图形保存到某处后,您可以使用 joblib 加载它,并使用 Graph 在 Dash 布局中使用它:

    fig = joblib.load("../example_codes/fig.pkl")
    
    app = dash.Dash()
    
    app.layout = html.Div([dcc.Graph(figure=fig)])
    
    if __name__ == "__main__":
        app.run_server(debug=True)
    

    【讨论】:

    • 在“import import dash_core_components as dcc”和“import dash_html_components as HTML”之后它起作用了。谢谢
    猜你喜欢
    • 2022-07-30
    • 2022-01-06
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2021-07-11
    相关资源
    最近更新 更多