475

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

import matplotlib.pyplot as plt
plt.plot([1,2,3],[5,7,4])
plt.show()

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 found and tried some advice to re-configure the "backend" mentioned in that warning, like so:

import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

but this gives me an error message:

ModuleNotFoundError: No module named 'tkinter'

I assumed that I had to install this module separately, but pip install tkinter does not work:

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

How can I make Matplotlib display the graph?


See also: Why does tkinter (or turtle) seem to be missing or broken? Shouldn't it be part of the standard library? . This question is not a duplicate, because the answers discuss other backends besides the Tkinter one.

Also see _tkinter.TclError: no display name and no $DISPLAY environment variable for issues with attempts to use Matplotlib remotely.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
johnwolf1987
  • 10,603
  • 3
  • 14
  • 17
  • 17
    Forget about the graph for a moment. Your problem is to install tkinter. Did you try any of the available solutions to that, e.g. https://stackoverflow.com/questions/4783810/install-tkinter-for-python ? – ImportanceOfBeingErnest Jun 18 '19 at 20:47
  • 4
    Are you actually using tkinter for anything, or did you just pick it as a plt backend? – G. Anderson Jun 18 '19 at 20:53
  • 1
    @ImportanceOfBeingErnest: Thank you for the hint. I will indeed focus on installing tkinter first. I will have a look at the link you provided and see if I can make anything out of it. – johnwolf1987 Jun 19 '19 at 20:17
  • 1
    @G.Anderson: I had no idea what tkinter was before I ran into this error with matplotlib. Now I am trying to install it just to be able to show graphs (so yes, I guess I just picked it as a plt backend). If you know of any other way (i.e. without using tkinter), I would be glad to hear it. – johnwolf1987 Jun 19 '19 at 20:19
  • There are [a number of backends](https://matplotlib.org/3.1.0/api/index_backend_api.html) you can use. [Here](https://stackoverflow.com/a/43015816/7835267) is an answer about cycling though backends until you find one that works with your installation – G. Anderson Jun 19 '19 at 20:24
  • @ImportanceOfBeingErnest: Thanks a lot for your help. I installed tkinter in the bash terminal using `apt-get install python3-tk` (from the link you sent me) and it seemed to have worked, as I can now display graphs. Also I don't need to import tkinter in my script. – johnwolf1987 Jun 19 '19 at 20:39
  • 2
    @G.Anderson: I ran the script to cycle through the different backends. It turns out that only TkAgg Is Available ! Indeed, I had just installed it prior to testing the script. – johnwolf1987 Jun 19 '19 at 20:41
  • Modern matplotlib versions will automatically cycle through available toolkits; so if tkinter isn't installed (and none of the other options are) it will fall back to `agg` backend. – ImportanceOfBeingErnest Jun 19 '19 at 21:32
  • On arch linux, `pacman -S --needed python-pyqt5` fixed the problem. – 8.8.8.8 Jan 14 '20 at 06:54
  • I face a similar problem and have managed to use anything **but** `Tcl/Tk` with python as reported [here](https://stackoverflow.com/a/65367570/1147688). IMO there must be a way to load Tcl/Tk as an external DLL and use the `tkinter` as an alias. – not2qubit Dec 19 '20 at 07:41

31 Answers31

564

Solution 1: is to install the GUI backend tk

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.

Solution 2: install any of the matplotlib supported GUI backends

  • solution 1 works fine because you get a GUI backend... in this case the TkAgg
  • however you can also fix the issue by installing any of the matplolib GUI backends like Qt5Agg, GTKAgg, Qt4Agg, etc
    • for example pip install pyqt5 will fix the issue also

NOTE:

  • usually this error appears when you pip install matplotlib and you are trying to display a plot in a GUI window and you do not have a python module for GUI display.
  • The authors of matplotlib made the pypi software deps not depend on any GUI backend because some people need matplotlib without any GUI backend.
Trevor Boyd Smith
  • 18,164
  • 32
  • 127
  • 177
johnwolf1987
  • 10,603
  • 3
  • 14
  • 17
  • 21
    Actually, I also realised that since I installed tkinter, I don't need to add the first two lines of my code anymore (`import matplotlib` and `matplotlib.use('TkAgg')`) – johnwolf1987 Jun 19 '19 at 21:03
  • 4
    For completeness, under OpenSuse Leap the package I had to install is called `python3-matplotlib-tk`. – Eldrad Jul 15 '20 at 18:54
  • 21
    This answer could probably mention that `tkinter` is python version-specific in the sense that this particular command will install `tkinter` exclusively for your default version of python. Suppose you have different python versions installations for various virtual envs. In that case, you will have to install it for the desired python version used in that working venv. For example, in my case: `sudo apt-get install python3.7-tk`. Not knowing this made me struggle a reasonable amount of time getting no module name ' tkinter' errors, even after installing it for my global python version. – xicocaio Aug 05 '20 at 20:41
  • I had to install a Linux Bash Terminal on my PC in order to run this command. And it worked! See https://www.howtogeek.com/249966/how-to-install-and-use-the-linux-bash-shell-on-windows-10/ – arame3333 Oct 27 '20 at 15:07
  • 7
    Or use `sudo apt-get install python3.8-tk` if your python version is 3.8 – Vicrobot Jan 03 '21 at 15:41
  • `matplotlib.use('TkAgg')` gave `[Previous line repeated 987 more times] RecursionError: maximum recursion depth exceeded` for me. I 'fixed' it by starting a new Python Console (in PyCharm). – Larry Cai Mar 04 '21 at 10:20
  • For Fedora: sudo dnf install python3-tkinter – Néstor Waldyd Apr 20 '21 at 00:50
  • pip how install tkinter? there are no corresponding item in search results. – Crawl.W Aug 06 '21 at 13:23
  • 1
    For me, "pip install tk" did not work (Im using windows 10). What worked is reinstalling pythin through downloaded executable, with the option "Modify", and then checking "tcl/tk and IDLE" checkbox. – NobodySomewhere Oct 13 '21 at 19:26
  • I have python 3.10 and on arch linux this works fine ``pip install pyqt5`` – Mahadev Gouda Aug 16 '22 at 12:55
  • Thanks !! pip install pyqt5 working for me python 3.9 , ubuntu 21.10 (but not sudo apt-get install python3-tk ) – Lingjing France Nov 09 '22 at 21:47
  • If you still facing this problem, be sure to put %matplotlib inline in your notebook AFTER the imports – diramazioni Mar 25 '23 at 12:00
137

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])
plt.savefig("mygraph.png")

I found the answer on a github repository.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
  • It doesn't really solve the underlying problem, but in my case this is the preferred solution in that it is better to save the image rather than show it, and this will often be the case. – arame3333 Mar 13 '21 at 19:11
57

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

sudo pacman -S tk

And all will work perfectly!

vvvvv
  • 25,404
  • 19
  • 49
  • 81
dexXxed
  • 681
  • 6
  • 8
  • 3
    I'm afraid to say this is like the 3rd time I end up here. Perhaps by commenting on it, I stand a better chance of remembering the "trick" next time I try this again... – logicOnAbstractions Dec 15 '21 at 22:16
51

Simple install

pip3 install PyQt5==5.9.2

It works for me.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Manish Gupta
  • 672
  • 6
  • 10
35

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

You can maybe try:

import tkinter
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('TkAgg')
plt.plot([1,2,3],[5,7,4])
plt.show()

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.

zby
  • 2,405
  • 1
  • 16
  • 12
okie
  • 847
  • 6
  • 18
  • 3
    Thank you for your suggestion. Unfortunately, it does not work (`ModuleNotFoundError: No module named 'tkinter'`). I will try to install tkinter some other way. – johnwolf1987 Jun 19 '19 at 20:15
  • I also encountered the same problem...I'm using linux so I have used this command to install the tkinter `sudo apt-get install python3-tk` – Senthuran Mar 20 '21 at 11:42
  • I have this issue which previously doesn't happen to me. I am using VS-code studio on Mac. – James Huang Jun 10 '22 at 13:55
  • Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure. – user3180 Aug 09 '23 at 20:41
27

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

vvvvv
  • 25,404
  • 19
  • 49
  • 81
chinelo Okafor
  • 269
  • 3
  • 2
  • 1
    This one finally worked for me after trying out everything else (installing tk, pyqt5, .use('tkagg'), manual imports, etc.). I use VSCode on Windows. – m_h Sep 20 '22 at 07:51
20

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

or

 sudo apt-get install python3-tk

For Centos users

 sudo yum install python-tkinter

or

 sudo yum install python3-tkinter

for Arch Users

  sudo pacman -S tk

or

  sudo pamac install tk

For Windows, use pip to install tk

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

Community
  • 1
  • 1
Arjun Kumar
  • 301
  • 2
  • 6
12

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' )


style.use("ggplot")
from sklearn import svm

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

plt.scatter(x,y)
plt.show()
flaxel
  • 4,173
  • 4
  • 17
  • 30
Kasut William
  • 129
  • 1
  • 2
  • This doesn't answer the question, because it specifically suggests an approach (`matplotlib.use( 'tkagg' )`) that OP already tried unsuccessfully. The question is about a) how to fix Tkinter so that this backend will work *or* b) how to use a different backend. – Karl Knechtel Apr 26 '23 at 15:33
8

For Windows 10, if using pip install tk does not work for you, try:

  • Download and run official python installer for windows. Even if you already have it downloaded, run it again.
  • When (re)installing python, make sure you chose "advanced" options, and set the checkbox "tcl/tk and IDLE" to true.
  • If you already had python installed, select the "Modify" option, and make sure that checkbox is selected.

Source of my fix: https://stackoverflow.com/a/59970646/2506354

NobodySomewhere
  • 2,997
  • 1
  • 16
  • 12
  • This was exactly the problem I had. Re-downloading the python installer for windows and adding this to the python installation via modify (after it had upgraded). No re-creation of virtualenvs was required. – Aesir Dec 21 '21 at 09:52
5

I installed python3-tk , on Ubuntu 20.04 and using WSL2

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib
    matplotlib.use( 'tkagg')

and then I installed GWSL from the Windows Store which seems to solve problem of WSL2 rendering out of the box

Agrover112
  • 461
  • 5
  • 9
5

None of these answers worked for me using Pycharm Professional edition 2021.3

Regular matplotlib graphs did work on the scientific view, but it did not allow me to add images to the plots.

What did work for me is adding this line before I try plotting anything:

plt.switch_backend('TkAgg')

knowledge_seeker
  • 811
  • 1
  • 8
  • 18
4

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
matplotlib.use('Qt5Agg')
buddemat
  • 4,552
  • 14
  • 29
  • 49
  • Worked for me on Ubuntu 16.04, PyCharm Prof – alexkaz Apr 09 '21 at 14:57
  • 1
    I think this is actually the right solution, because it is the easiest. Only need to install it where needed, e.g. by running : pip3 install PyQt5 – Gregor Nov 25 '21 at 14:31
3

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.

Hari
  • 1,561
  • 4
  • 17
  • 26
3

I have solved it by putting matplotlib.use('TkAgg') after all import statements. I use python 3.8.5 VSCODE and anaconda. No other tricks worked.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Dpappala
  • 39
  • 2
3

On Mac OS, I made it work with:

import matplotlib
matplotlib.use('MacOSX')
lubumbax
  • 255
  • 2
  • 9
2

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.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Divas
  • 455
  • 2
  • 7
  • 14
2

On WSL with X server

Make sure that your X server work. Matplotlib indicate this error if he can't connect to the X display.

Windows Firewall configuration

Pay attention to the windows firewall ! I changed from WSL Debian to Ubuntu and didn't remember about the firewall rule. I use this post to configure the windows firewall rule to make the X server work. This method avoid too permisive rule that able anyone to use your X server.

It said :

If you already had installed an X11 server, Windows may have created firewall rules that will mess with the above configuration. Search for them and delete them in "Windows Defender Firewall with Advanced Security."

You will now need to configure Windows Firewall to permit connections from WSL2 to the X11 display server. You will install the display server in the next step. We do this step first to avoid Windows Firewall from auto-creating an insecure firewall rule when you run the X11 display server. Many guides on X11 forwarding and WSL2 make this firewall rule too permissive, allowing connections from any computer to your computer. This means someone could theoretically, if they are on your same network, start sending graphical display information to your computer.

To avoid this, we will make Windows Firewall only accept internet traffic from the WSL2 instance.

To set this up, you can copy the below to a script and run it from within WSL2:

#!/bin/sh
LINUX_IP=$(ip addr | awk '/inet / && !/127.0.0.1/ {split($2,a,"/"); print a[1]}')
WINDOWS_IP=$(ip route | awk '/^default/ {print $3}')
# Elevate to administrator status then run netsh to add firewall rule
powershell.exe -Command "Start-Process netsh.exe -ArgumentList \"advfirewall firewall add rule name=X11-Forwarding dir=in action=allow program=%ProgramFiles%\VcXsrv\vcxsrv.exe localip=$WINDOWS_IP remoteip=$LINUX_IP localport=6000 protocol=tcp\" -Verb RunAs"

Manual method :

Alternatively, you can manually add the rule through a GUI by doing the following:

  1. Open "Windows Defender Firewall with Advanced Security"
  2. Click add new rule brings up the New Rule Wizard (next to navigate between each section):
    • Rule type: Custom
    • Program: "This program path:" %ProgramFiles%\VcXsrv\vcxsrv.exe
    • Protocol and ports
    • Protocol type: TCP
    • Local port: 6000
    • Remote port: any
    • Scope
      • Local IP address: Obtain the IP address to put in by running the below command in WSL2 ip route | awk '/^default/ {print $3}'
    • remote IP addresses
      • Obtain IP address to enter by running the below in WSL2 ip addr | awk '/inet / && !/127.0.0.1/ {split($2,a,"/"); print a[1]}'
    • Action: "Allow the connection
    • Profile: Selection Domain, Private, and Public
    • Name: "X11 forwarding"
Charles Attend
  • 51
  • 1
  • 1
  • 4
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/31039990) – Simas Joneliunas Feb 17 '22 at 02:55
1

If you install python versions using pyenv on Debian-based systems, be sure to run sudo apt install tk-dev before pyenv install. If it's already installed, remove it with pyenv uninstall and install it again after install tk-dev. Therefore, there is no need to set any env variables when running pyenv install.

Fábio
  • 771
  • 2
  • 14
  • 25
1

Ubuntu 20.04 command line setup. I install the following to make Matplotlib stop throwing the error UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.

I installed python-tk through the steps:

apt-get update

apt-get install python3.8-tk
GigaWatts
  • 101
  • 8
0

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.

Mohd
  • 81
  • 1
  • 8
0

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

matplotlib.use('TKAgg',warn=False, force=True)
Shahir Ansari
  • 1,682
  • 15
  • 21
  • This does not answer the question, because it describes an approach that OP already tried unsuccessfully before posting. – Karl Knechtel Apr 26 '23 at 15:40
0

Works if you use some third party code in your project. It probably contains the following line

matplotlib.use('Agg')

Search for it and comment it out.

If you have no clue about what it is you are probably not using this part of the code.

Solutions about using another backend GUI may be cleaner, so choose your fighter.

0

The solution that worked for me:

  1. Install tkinter

  2. import tkinter into the module

  3. make sure that matplotlib uses (TkAgg) instead of (Agg)

    matplotlib.use('TkAgg')

Vega
  • 27,856
  • 27
  • 95
  • 103
  • This does not answer the question, because it describes an approach that OP already tried unsuccessfully before asking. (It also effectively duplicates a couple other answers.) – Karl Knechtel Apr 26 '23 at 15:38
0

Beware of the import order in your code, I spent a whole day going through this answers and ended up solving the problem by importing bt before anything else and then using the .use('TkAgg') statement (for some reason importing bt changes the matplotlib backend to 'Agg')

Simas Joneliunas
  • 2,890
  • 20
  • 28
  • 35
0

Another option is to install Anaconda. It is a useful software where you can create many environments and there are many libraries already installed for data science and machine learning.

--Edit --

Here there are steps that help me to fix your same issue:

  • Step 1: Download .exe on the official page: Anaconda, use the individual edition because it is the free ones: Anaconda Individual
  • Step 2: Once you have installed the program, open in end go to the env section enter image description here

In this section, you can create many env as you prefer, i.e I have 2 env one for my main base (root) one for the last version of python.

  • Step 3: creating the py env in this section, Anaconda will install automatically the main libraries used by developers, decreasing the risk of getting Errors on your code.

  • Additional Consideration: as you can see in the snap below you can easily see which libraries have you installed in your conda. I got your same that error because i missed one of that 3 libs enter image description here

Hope was useful and clear to understand! Cya

  • 1
    This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/30066500) – Gino Mempin Oct 13 '21 at 13:24
  • Sir, Q: he was not able to see the chart correctly. A: By installing the software you are able to fix that problem. I had the same problem and this was how I fixed it in my personal experience. Thanks. –  Oct 13 '21 at 14:29
  • 1
    Then please [edit] to add more details and steps to your answer, which is basically "install anaconda". Installing Anaconda is *just the 1st step*. How does it solve the problem with matplotlib and tkinter? How do they install the other packages? What specific commands do they need to run? It's missing some more details to make it a full answer. – Gino Mempin Oct 14 '21 at 08:16
0

Running %matplotlib inline Once fixed the problem for me. I found the answer here: When I use matplotlib in jupyter notebook,it always raise " matplotlib is currently using a non-GUI backend" error? by user Mulugeta Weldezgina

adding %matplotlib inline while importing helps for smooth plots in notebook

%matplotlib inline
import matplotlib.pyplot as plt

%matplotlib inline sets the backend of matplotlib to the 'inline' backend: With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.

My problem started after I used pandas_profile (or something like that), and running %matplotlib inline once fixed the background from being headless etc.

user96265
  • 510
  • 5
  • 6
0

I have had the same problem with Windows 7 and PyCharm Pro. It happened after I'd installed the financial package "ffn", so after

import ffn

the Matplotlib backend had changed to "add". You can check the current backend by:

matplotlip.get_backend()

You can change the current backend by:

matplotlib.use(backend = "module://backend_interagg")

Which worked for my issue with PyCharm Professional in an additional or internal window.

Bem Ostap
  • 61
  • 4
0

For Windows, check this box during setup: enter image description here

товіаѕ
  • 2,881
  • 4
  • 23
  • 53
-1

Linux Mint 19. Helped for me:

sudo apt install tk-dev

P.S. Recompile python interpreter after package install.

-1

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.

GuyStalks
  • 169
  • 1
  • 5
-1

the solution of this problem is: make sure put this line

%matplotlib inline

in the head of your code

like that

# In an IPython notebook¶
# This magic just sets up matplotlib's interactive mode
%matplotlib inline
# So you have to explicitely import the module into the namespace
import matplotlib.pyplot as pl
import numpy as np
# Create the figure object
fig = pl.figure(figsize=(12, 8))
x = np.arange(0, 4 * np.pi, 0.1)
y = np.sin(x)
pl.plot(x, y)

%matplotlib inline turns on “inline plotting”, where plot graphics will appear in your notebook. This has important implications for interactivity: for inline plotting, commands in cells below the cell that outputs a plot will not affect the plot. For example, changing the color map is not possible from cells below the cell that creates a plot. However, for other backends, such as qt4, that open a separate window, cells below those that create the plot will change the plot - it is a live object in memory. If you are not using matplotlib in interactive mode at all, figures will only appear if you invoke

for more information about %matplotlib inline see this link

Chafik Boulealam
  • 516
  • 5
  • 10