Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plt.savefig() in Python crashes with .jpg format even after installing pillow

I'm trying to save a figure with plt.savefig() is python as a jpg or jpeg format but I keep having this error:

File "/home/user/.local/lib/python3.7/site-packages/matplotlib/backends/backend_gtk3.py", line 468, in set_cursor
    self.canvas.get_property("window").set_cursor(cursord[cursor])

AttributeError: 'NoneType' object has no attribute 'set_cursor'

Pillow is installed and these are the supposed formats of images supported by matplotlib 3.2.1 on my computer: (supported formats: eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff)

The code works properly with other formats like pdf or png. This is my code (very simple):

import matplotlib.pyplot as plt
plt.plot([0, 1, 2, 3, 4], [0, 3, 5, 9, 11])
plt.xlabel('Months')
plt.ylabel('Books Read')
plt.savefig('book.jpg')
like image 272
Hypatia Avatar asked Oct 27 '25 11:10

Hypatia


1 Answers

If you don't intend to use plt.show() then simply add the following:

import matplotlib
matplotlib.use('Agg')

book.jpg:

plot

EDIT:

Looking at the documentation linked to in my comment below

you should avoid explicitly calling use() unless absolutely necessary.

Instead you can create a matplotlibrc file in the same directory as your script and change the backend that way by adding backend : Agg or backend : TkAgg to that file.

like image 77
compuphys Avatar answered Oct 30 '25 00:10

compuphys



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!