【问题标题】:AttributeError: 'Figure' object has no attribute savefig in FlaskAttributeError:“Figure”对象在 Flask 中没有属性 savefig
【发布时间】:2020-04-11 17:09:49
【问题描述】:

我正在尝试在 Flask 中显示 plotly.express 条形图。但它给了'Figure' object has no attribute savefig error。使用fig.show() 时图像会正确显示。

import matplotlib.pyplot as plt
import plotly.express as px

figs = px.bar(
    comp_df.head(10),
    x = "Company",
    y = "Staff",
    title= "Top 10 departments",
    color_discrete_sequence=["blue"],
    height=500,
    width=800
)
figs.savefig('static/images/staff_plot.png')
#    fig.show()
return render_template('plot.html', name='new_plot', url='static/images/staff_plot.png')

plot.html中,图片显示如下:

<img src={{ url}} >

【问题讨论】:

    标签: python-3.x flask plotly-python plotly-express


    【解决方案1】:

    您已经使用px.bar() 方法定义了figs

    documentation px.bar() 返回一个plotly.graph_objects.Figure 对象。

    查看这个plotly.graph_objects.Figure 类的文档,我们可以看到这个plotly.graph_objects.Figure 类的所有可用方法。 show() 似乎是此类对象的有效方法。但是这个类没有savefig() 方法。 这就是fig.show() 有效而fig.savefig() 无效的原因。

    matplotlib.pyplot 类上似乎有一个savefig() 方法documented here,但是您的figs 对象是plotly.graph_objects.Figure 的实例而不是matplotlib.pyplot

    如果您的目标是将您的 figs 对象写入文件,那么文档似乎指定了提供此功能的 3 种方法:

    plotly.graph_objects.Figure

    尝试替换:

    figs.savefig('static/images/staff_plot.png')

    figs.write_image(file='static/images/staff_plot.png', format='.png')

    【讨论】:

    • 谢谢。使用 write_image 时,出现错误“需要 Orca 模块”
    • 谢谢。图像正在显示,但当我将鼠标悬停在栏上时未显示工具提示。也许是因为它只是一个图像,但它看起来不太互动
    • 对不起,我帮不上忙。我从未真正使用过这些库中的任何一个。
    【解决方案2】:

    不要使用figs.savefig,而是尝试使用plt.savefig

    import matplotlib.pyplot as plt
    plt.savefig('static/images/staff_plot.png')
    

    【讨论】:

    • 我已投票删除此答案,因为它不正确。 figsplotly.express 对象,而不是 matplotlib 对象
    猜你喜欢
    • 1970-01-01
    • 2020-01-07
    • 2019-11-27
    • 1970-01-01
    • 2014-11-11
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多