[python] "UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm

I am trying to plot a simple graph using pyplot, e.g.:

import matplotlib.pyplot as plt

but the figure does not appear and I get the following message:

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

I saw in several places that one had to change the configuration of matplotlib using the following:

import matplotlib
import matplotlib.pyplot as plt

I did this, but then got an error message because it cannot find a module:

ModuleNotFoundError: No module named 'tkinter'

Then, I tried to install "tkinter" using pip install tkinter (inside the virtual environment), but it does not find it:

Collecting tkinter
  Could not find a version that satisfies the requirement tkinter (from versions: )
No matching distribution found for tkinter

I should also mention that I am running all this on Pycharm Community Edition IDE using a virtual environment, and that my operating system is Linux/Ubuntu 18.04.

I would like to know how I can solve this problem in order to be able to display the graph.

This question is related to python matplotlib pycharm

The answer is

I found a solution to my problem (thanks to the help of ImportanceOfBeingErnest).

All I had to do was to install tkinter through the Linux bash terminal using the following command:

sudo apt-get install python3-tk

instead of installing it with pip or directly in the virtual environment in Pycharm.

In my case, the error message was implying that I was working in a headless console. So plt.show() could not work. What worked was calling plt.savefig:

import matplotlib.pyplot as plt

plt.plot([1,2,3], [5,7,4])

I found the answer on a github repository.

If you use Arch Linux (distributions like Manjaro or Antegros) simply type:

sudo pacman -S tk

And all will work perfectly!

Try import tkinter because pycharm already installed tkinter for you, I looked Install tkinter for Python

You can maybe try:

import tkinter
import matplotlib

as a tkinter-installing way

I've tried your way, it seems no error to run at my computer, it successfully shows the figure. maybe because pycharm have tkinter as a system package, so u don't need to install it. But if u can't find tkinter inside, you can go to Tkdocs to see the way of installing tkinter, as it mentions, tkinter is a core package for python.

Simple install

pip3 install PyQt5==5.9.2

It works for me.

I too had this issue in PyCharm. This issue is because you don't have tkinter module in your machine.

To install follow the steps given below (select your appropriate os)

For ubuntu users

 sudo apt-get install python-tk


 sudo apt-get install python3-tk

For Centos users

 sudo yum install python-tkinter


 sudo yum install python3-tkinter

For Windows, use pip to install tk

After installing tkinter restart your Pycharm and run your code, it will work

This worked with R reticulate. Found it here.

1: matplotlib.use( 'tkagg' ) or 2: matplotlib$use( 'tkagg' )

For example:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style

import matplotlib
matplotlib.use( 'tkagg' )

from sklearn import svm

x = [1, 5, 1.5, 8, 1, 9]
y = [2, 8, 1.8, 8, 0.6, 11]


I added %matplotlib inline and my plot showed up in Jupyter Notebook.

After upgrading lots of packages (Spyder 3 to 4, Keras and Tensorflow and lots of their dependencies), I had the same problem today! I cannot figure out what happened; but the (conda-based) virtual environment that kept using Spyder 3 did not have the problem. Although installing tkinter or changing the backend, via matplotlib.use('TkAgg) as shown above, or this nice post on how to change the backend, might well resolve the problem, I don't see these as rigid solutions. For me, uninstalling matplotlib and reinstalling it was magic and the problem was solved.

pip uninstall matplotlib

... then, install

pip install matplotlib

From all the above, this could be a package management problem, and BTW, I use both conda and pip, whenever feasible.

The comment by @xicocaio should be highlighted.

tkinter is python version-specific in the sense that sudo apt-get install python3-tk will install tkinter exclusively for your default version of python. Suppose you have different python versions within various virtual environments, you will have to install tkinter for the desired python version used in that virtual environment. For example, sudo apt-get install python3.7-tk. Not doing this will still lead to No module named ' tkinter' errors, even after installing it for the global python version.

Just in case if this helps anybody.

Python version: 3.7.7 platform: Ubuntu 18.04.4 LTS

This came with default python version 3.6.9, however I had installed my own 3.7.7 version python on it (installed building it from source)

tkinter was not working even when the help('module') shows tkinter in the list.

The following steps worked for me:

  1. sudo apt-get install tk-dev.

rebuild the python: 1. Navigate to your python folder and run the checks:

cd Python-3.7.7
sudo ./configure --enable-optimizations
  1. Build using make command: sudo make -j 8 --- here 8 are the number of processors, check yours using nproc command.
  2. Installing using:

    sudo make altinstall

Don't use sudo make install, it will overwrite default 3.6.9 version, which might be messy later.

  1. Check tkinter now
    python3.7 -m tkinter

A windows box will pop up, your tkinter is ready now.

When I ran into this error on Spyder, I changed from running my code line by line to highlighting my block of plotting code and running that all at once. Voila, the image appeared.

You can change the matplotlib using backend using the from agg to Tkinter TKAgg using command

matplotlib.use('TKAgg',warn=False, force=True)

Linux Mint 19. Helped for me:

sudo apt install tk-dev

P.S. Recompile python interpreter after package install.

issue = “UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.”

And this worked for me

import matplotlib
import matplotlib.pyplot as plt

Questions with python tag:

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Upgrade to python 3.8 using conda Unable to allocate array with shape and data type How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip How to prevent Google Colab from disconnecting? "UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function? "E: Unable to locate package python-pip" on Ubuntu 18.04 Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session' Jupyter Notebook not saving: '_xsrf' argument missing from post How to Install pip for python 3.7 on Ubuntu 18? Python: 'ModuleNotFoundError' when trying to import module from imported package OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this? Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website How to setup virtual environment for Python in VS Code? Pylint "unresolved import" error in Visual Studio Code Pandas Merging 101 Numpy, multiply array with scalar What is the meaning of "Failed building wheel for X" in pip install? Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed Could not install packages due to an EnvironmentError: [Errno 13] OpenCV !_src.empty() in function 'cvtColor' error ConvergenceWarning: Liblinear failed to converge, increase the number of iterations How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How do I install opencv using pip? How do I install Python packages in Google's Colab? How do I use TensorFlow GPU? How to upgrade Python version to 3.7? How to resolve TypeError: can only concatenate str (not "int") to str How can I install a previous version of Python 3 in macOS using homebrew? Flask at first run: Do not use the development server in a production environment TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array What is the difference between Jupyter Notebook and JupyterLab? Pytesseract : "TesseractNotFound Error: tesseract is not installed or it's not in your path", how do I fix this? Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'" How do I resolve a TesseractNotFoundError? Trying to merge 2 dataframes but get ValueError Authentication plugin 'caching_sha2_password' is not supported Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

Questions with matplotlib tag:

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm How to increase image size of pandas.DataFrame.plot in jupyter notebook? How to create a stacked bar chart for my DataFrame using seaborn? How to display multiple images in one figure correctly? Edit seaborn legend How to hide axes and gridlines in Matplotlib (python) How to set x axis values in matplotlib python? How to specify legend position in matplotlib in graph coordinates Python "TypeError: unhashable type: 'slice'" for encoding categorical data Seaborn Barplot - Displaying Values Purpose of "%matplotlib inline" How to make two plots side-by-side using Python? Why plt.imshow() doesn't display the image? Add Legend to Seaborn point plot Change line width of lines in matplotlib pyplot legend How to add title to seaborn boxplot How to plot vectors in python using matplotlib How to plot an array in python? matplotlib: plot multiple columns of pandas data frame on the bar chart TypeError: 'DataFrame' object is not callable Plotting images side by side using matplotlib How to change the plot line color from blue to black? Pandas dataframe groupby plot FutureWarning: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison Matplotlib - How to plot a high resolution graph? Python & Matplotlib: Make 3D plot interactive in Jupyter Notebook _tkinter.TclError: no display name and no $DISPLAY environment variable matplotlib: how to draw a rectangle on image Plotting a python dict in order of key values Hide axis values but keep axis tick labels in matplotlib How to draw a line with matplotlib? TypeError: Invalid dimensions for image data when plotting array with imshow() What's the fastest way of checking if a point is inside a polygon in python How to make inline plots in Jupyter Notebook larger? matplotlib error - no module named tkinter Fine control over the font size in Seaborn plots for academic papers %matplotlib line magic causes SyntaxError in Python script How can I plot a confusion matrix? Plotting lines connecting points Display an image with Python Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python Python: How to increase/reduce the fontsize of x and y tick labels? Plot a horizontal line using matplotlib Plotting a 2D heatmap with Matplotlib How to set the range of y-axis for a seaborn boxplot? How to plot a histogram using Matplotlib in Python with a list of data? Modify the legend of pandas bar plot Add colorbar to existing axis How to save a Seaborn plot into a file How to rotate x-axis tick labels in Pandas barplot

Questions with pycharm tag:

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website Pycharm/Python OpenCV and CV2 install error Import numpy on pycharm Global npm install location on windows? Pycharm and sys.argv arguments PyCharm error: 'No Module' when trying to import own module (python script) Using (Ana)conda within PyCharm Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script How to run PyCharm in Ubuntu - "Run in Terminal" or "Run"? ImportError: No module named 'bottle' - PyCharm tkinter: how to use after method Pycharm does not show plot PyCharm import external library Why does pycharm propose to change method to static Pycharm: run only part of my Python file Cannot find reference 'xxx' in __init__.py - Python / Pycharm How do I activate a virtualenv inside PyCharm's terminal? Launch Pycharm from command line (terminal) Unresolved reference issue in PyCharm What is the problem with shadowing names defined in outer scopes? How do I use installed packages in PyCharm? Trying to get PyCharm to work, keep getting "No Python interpreter selected" How to my "exe" from PyCharm project How do I set the maximum line length in PyCharm? How to configure custom PYTHONPATH with VM and PyCharm? pycharm convert tabs to spaces automatically PyCharm shows unresolved references error for valid code pycharm running way slow How to select Python version in PyCharm? How to make PyCharm always show line numbers Is there a difference between using a dict literal and a dict constructor? How do I configure PyCharm to run py.test tests?