Reputation: 750
I am trying to display plotly.express
bar chart in Flask. But it is giving 'Figure' object has no attribute savefig error
. The image gets displayed correctly while using 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')
In plot.html
, the image is displayed as below:
<img src={{ url}} >
Upvotes: 4
Views: 18597
Reputation: 11
Instead of using figs.savefig
, try to use plt.savefig
import matplotlib.pyplot as plt
plt.savefig('static/images/staff_plot.png')
Upvotes: -1
Reputation: 2638
You have defined figs
with the px.bar()
method.
Per documentation px.bar()
returns a plotly.graph_objects.Figure
object.
Looking at this plotly.graph_objects.Figure
class' documentation we can see all the methods available on this plotly.graph_objects.Figure
class.
show()
appears to be a valid method for this type of object. However there is no savefig()
method for this class.
This is why fig.show()
works and fig.savefig()
doesn't work.
It looks like there is a savefig()
method on the matplotlib.pyplot
class as documented here, however your figs
object is an instance of plotly.graph_objects.Figure
not matplotlib.pyplot
.
If your goal is to write your figs
object to a file, it looks like the documentation specifies 3 methods that provide this functionality:
plotly.graph_objects.Figure
Try replacing:
figs.savefig('static/images/staff_plot.png')
with
figs.write_image(file='static/images/staff_plot.png', format='.png')
Upvotes: 6