Joh*_*ohn 4 flask python-3.x plotly-python plotly-express
我正在尝试在 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')
Run Code Online (Sandbox Code Playgroud)
中plot.html,图像显示如下:
<img src={{ url}} >
Run Code Online (Sandbox Code Playgroud)
你已经figs用px.bar()方法定义了。
每个文档 px.bar()返回一个plotly.graph_objects.Figure对象。
查看此类plotly.graph_objects.Figure的文档,我们可以看到此类上所有可用的方法plotly.graph_objects.Figure。
show()似乎是此类对象的有效方法。savefig()但是这个类没有方法。这就是为什么fig.show()有效和fig.savefig()无效的原因。
看起来该类有一个savefig()方法,matplotlib.pyplot如此处记录的,但是您的对象是notfigs的实例。plotly.graph_objects.Figurematplotlib.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')