Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: 'Figure' object has no attribute savefig in Flask

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}} >
like image 979
John Avatar asked Sep 02 '25 10:09

John


1 Answers

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

  • write_html
  • write_image
  • write_json

Try replacing:

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

with

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

like image 147
steve Avatar answered Sep 05 '25 00:09

steve