PyCharm Matplotlib "UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure. plt.show()"

Question:

I am having problems with matplotlib.pyplot.show() function. I am using PyCharm on Linux, and i have a VirtualEnv. When i execute the file x.py in the built terminal in PyCharm (using venv) like this

$ python x.py

everything works fine, the function plt.show() renders and shows the plotted graph well. i did add print(matplotlib.get_backend()) to see which backend was used by default and the result was GTK3Agg.

The problem starts when i use the option Run and not the terminal. Then i get an error message

UserWarning: Matplotlib is currently using agg, which is a non-GUI
backend, so cannot show the figure. plt.show()

Anyways, i searched online and according to this and other links, i had to add backend: GTK3Agg in .config/matplotlib/matplotlibrc . The file did not exist so i created it myself. Now when i run again, i get the following error messages:

raise ImportError('backend Gtk3Agg requires cairo') from e ImportError: backend Gtk3Agg requires cairo

How can i fix this ?

Asked By: user2719475

||

Answers:

I managed to solve my problem, thanks to @ImportanceOfBeingErnest pointing out that i had two environments, one where GTK and dependencies are installed, and one, which is used by PyCharm, where those are missing.

I had to go to Settings > Project interpreter and install matplotlib, pycairo and PyGObject.

Also neccessary to install pycairo and PyGObject were these packages, which i had to install from the terminal:

sudo dnf install cairo-devel (or libcairo2 in ubuntu)
sudo dnf install python3-devel
sudo dnf install gobject-introspection-devel
sudo dnf install cairo-gobject-devel

Now i can use GTK3Agg as my backend.

Answered By: user2719475

In my case (Linux Mint 20.3) the issue came from installing PyCharm from the Software Manager. PyCharm then was installed with flatpak

flatpak list

should give show you an idea if it is so too.

There are issues with that version. Have a look at:
https://github.com/flathub/com.jetbrains.PyCharm-Community/issues/15

I could fix it by installing PyCharm with snapd.
https://thesecmaster.com/3-ways-to-install-pycharm-on-linux-mint-and-ubuntu/

then: sudo apt-get install python3.8-tk
and within PyCharm I had to add

"future" and "matplotlib"

More information about it:
When you run PyCharm the first time (installed from Software Manager) you receive:

https://www.flathub.org


| Warning: You are running an unofficial Flatpak version of PyCharm !!! |

Please open issues under: https://github.com/flathub/com.jetbrains.PyCharm-Community/issues

This version is running inside a container and is therefore not able
to access SDKs on your host system!

Answered By: Alles Klar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.