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 saw in several places that one had to change the configuration of matplotlib using the following:
import matplotlib
matplotlib.use('TkAgg')
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.
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.
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.
If you use Arch Linux (distributions like Manjaro or Antegros) simply type:
sudo pacman -S tk
And all will work perfectly!
Simple install
pip3 install PyQt5==5.9.2
It works for me.
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.
I added %matplotlib inline
and my plot showed up in Jupyter Notebook.
The answer has been given a few times but it is not obvious, one needs to install graphics, this works.
pip3 install PyQt5
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
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()
If using Jupyter notebook try the following:
%matplotlib inline
This should render the plot even if not specifying the
plt.show()
command.
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')
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')
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
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.
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
This will solve the issue. It works well in jupyter.
%matplotlib inline
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.
On Mac OS, I made it work with:
import matplotlib
matplotlib.use('MacOSX')
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
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:
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
Build using make command:
sudo make -j 8 --- here 8 are the number of processors, check yours using nproc command.
Installing using:
sudo make altinstall
Don't use sudo make install, it will overwrite default 3.6.9 version, which might be messy later.
Check tkinter now
python3.7 -m tkinter
A windows box will pop up, your tkinter is ready now.
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.
You can change the matplotlib using backend using the from agg to Tkinter TKAgg using command
matplotlib.use('TKAgg',warn=False, force=True)
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.
The solution that worked for me:
Install tkinter
import tkinter into the module
make sure that matplotlib uses (TkAgg) instead of (Agg)
matplotlib.use('TkAgg')
execute the following command before plotting
%matplotlib inline
Try:
%matplotlib inline
I had the same problem and it worked for me. I tested it on my Jupyter notebooks and visual studio code, so you should have no problems.
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:
Open "Windows Defender Firewall with Advanced Security"
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"
Linux Mint 19. Helped for me:
sudo apt install tk-dev
P.S. Recompile python interpreter after package install.
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.
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.
Can you shed some light on the interaction between the Python interpreter distributed with OS X and the one that can be installed through MacPorts?
While installing networkx and matplotlib I am having difficulties with the interaction of /usr/bin/python and /opt/local/bin/python2.7. (The latter is itself a soft pointer to /opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7)
How can I be certain which Python, pip, and Python libraries I am using at any one time?
More importantly, it appears that installing matplotlib is not possible on Lion. It fails with Requires numpy 1.6 or later to build. (Found 1.5.1). If I upgrade by running sudo pip install --upgrade numpy, it does not help. Subsequently attempting to install matplotlib (sudo /usr/local/bin/pip install matplotlib) still fails with the same (Requires numpy 1.6...) message. How can I install matplotlib?
Points to keep in mind about Python
If a script foobar.py starts with #!/usr/bin/env python, then you will always get the OS X Python. That's the case even though MacPorts puts /opt/local/bin ahead of /usr/bin in your path. The reason is that MacPorts uses the name python2.7. If you want to use env and yet use MacPorts Python, you have to write #!/usr/bin/env python2.7.
If a script foobar.py starts explicitly with #!/usr/bin/python or with #!/opt/local/bin/python2.7, then the corresponding Python interpreter will be used.
What to keep in mind about pip
To install pip for /usr/bin/python, you need to run sudo /usr/bin/easy_install pip. You then call pip (which will not be installed by easy_install in /usr/bin/pip, but rather in /usr/local/bin/pip)
To install pip for /opt/local/bin/python2.7, you need to run sudo port install py27-pip. You would then call pip-2.7. You will get the pip in /opt/local/bin. Be careful, because if you type pip2.7 you will get /usr/local/bin/pip2.7 (the OS X pip).
Installing networkx and matplotlib
To install networkx for the OS X Python you would run sudo /usr/local/bin/pip install networkx. I don't know how to install matplotlib on OS X Lion. It may be that OS X has to stick to numpy 1.5.1 because it uses it internally.
To install networkx and matplotlib for MacPorts-Python, call sudo pip-2.7 install networkx and sudo pip-2.7 install matplotlib. matplotlib installs with a lot of warnings, but it passes.
May I also suggest using Continuum Analytics "anaconda" distribution. One benefit in doing so would be that you won't then need to modify he standard OS X python environment.
I'm using Python 2.7.3 in 64-bit. I installed pandas as well as matplotlib 1.1.1, both for 64-bit. Right now, none of my plots are showing. After attempting to plot from several different dataframes, I gave up in frustration and tried the following first example from http://pandas.pydata.org/pandas-docs/dev/visualization.html:
INPUT:
import matplotlib.pyplot as plt
ts = Series(randn(1000), index=date_range ('1/1/2000', periods=1000))
ts = ts.cumsum()
ts.plot()
pylab.show()
OUTPUT:
Axes(0.125,0.1;0.775x0.8)
And no plot window appeared. Other StackOverflow threads I've read suggested I might be missing DLLs. Any suggestions?
I'm not convinced this is a pandas issue at all.
Does
import matplotlib.pyplot as plt
plt.plot(range(10))
plt.show()
bring up a plot?
If not:
How did you install matplotlib? Was it from source or did you install it from a package manager/pre-built binary?
I suspect that if you run:
import matplotlib
print matplotlib.rcParams['backend']
The result will be a non-GUI backend (almost certainly "Agg"). This suggests you don't have a suitable GUI toolkit available (I personally use Tkinter which means my backend is reported as "TkAgg").
The solution to this depends on your operating system, but if you can install a GUI library (one of Tkinter, GTK, QT4, PySide, Wx) then pyplot.show() should hopefully pop up a window for you.
HTH,
I had this problem when working from within a virtualenv.
Cause
The cause of the problem is that when you pip install matplotlib, it fails to find any backends (even if they are installed on your machine), so it uses the "agg" backend, which does not make any plots, just writes files. To confirm that this is the case, go: python -c "import matplotlib; print matplotlib.get_backend()", you probably see agg.
I could however, successfully use matplotlib on the system (outside the virtualenv). I also failed to install PySide, PyQt, or get it to work for TkAgg, for various different reasons.
Solution
I eventually just made a link to my system version of matplotlib (starting from outside the venv):
...$ pip install matplotlib
...$ cd /to/my/venv/directory
...$ source venv/bin/activate
(venv) .... $ pip uninstall matplotlib
(venv) .... $ ln -s /usr/lib/pymodules/python2.7/matplotlib $VIRTUAL_ENV/lib.python*/site-packages
After that, I could use matplotlib and the plots would show. Your local version of matplotlib may be in a different place. To see where it is, go (outside of the venv, in python)
...$ python -c 'import matplotlib; matplotlib.__file__'
Try installing these libraries, it works for me:
$ sudo apt-get install tcl-dev tk-dev python-tk python3-tk
I am trying to install MayaVi on my computer. I'm on a MacBook Air with OS X 10.6.8, 4 GB RAM.
My python and most of my stack is built through Homebrew or pip. In particular this is true for python2.7, ipython, Qt4, numpy, scipy, vtk, etc. VTK was installed with --python and --qt-extern flags in Homebrew, and all the builds were fine. I do not have wxPython installed, as I failed to get it working through pip, manual building, or the binaries.
If I run ipython -q4thread, I cannot successfully execute from mayavi import mlab as I get an error related to usage of two different APIs for PyQt: http://groups.google.com/group/spyderlib/browse_thread/thread/36a35baec74ca144
However, if I run ipython alone, I can successfully run from mayavi import mlab. Then I try to follow this example: http://github.enthought.com/mayavi/mayavi/example_using_with_scipy.html, which includes these commands:
import numpy as np
def V(x, y, z):
""" A 3D sinusoidal lattice with a parabolic confinement. """
return np.cos(10*x) + np.cos(10*y) + np.cos(10*z) + 2*(x**2 + y**2 + z**2)
X, Y, Z = np.mgrid[-2:2:100j, -2:2:100j, -2:2:100j]
from mayavi import mlab
mlab.contour3d(X, Y, Z, V)
This all works fine, and I get a window that pops up and I can rotate the 3d plot etc. However, then I click on the icon to open up the pipeline, which opens another window. The tutorial then says to double-click on the "isosurface" to change its properties. As soon as I do that, I get a reproducible segmentation fault.
I have no idea how to begin to figure out what the problem is.
Alternatively, I can run MayaVi from the command line: mayavi2, and the GUI pops up. When I do so I get the following output:
Warning: Unable to import the wx backend for pyface due to traceback: Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.1/lib/python2.7/site-packages/pyface/toolkit.py", line 45, in _init_toolkit
be = import_toolkit(tk)
File "/usr/local/Cellar/python/2.7.1/lib/python2.7/site-packages/pyface/toolkit.py", line 31, in import_toolkit
__import__(be + 'init')
File "/usr/local/Cellar/python/2.7.1/lib/python2.7/site-packages/pyface/ui/wx/init.py", line 14, in <module>
import wx
ImportError: No module named wx
Although the GUI does pop up, if I try to do any operation, I get a segfault.
Please let me know if you have any thoughts on troubleshooting this, or perhaps guidance on reinstalling the package successfully.
Thanks!
Uri
I also have a MacBook Air with OS X 10.7.4 (Lion). I spent a lot of time back in February to get mayavi working, eventually succeeding to a point where I could produce scientific plots. That still means that some of the examples and tests wouldn't run correctly, and the GUI produced lots of error messages in the console, but didn't crash (most of the time). Now, I managed to break my Python installation (probably by upgrading numpy), so I needed to reinstall. Alas, it didn't get any easier 6 months later!
There is still no viable precompiled option. I tried the Enthought Python Distribution from here: http://www.enthought.com/repo/.epd_academic_installers. Still no 64 bit version with ETS for Mac, components are ancient, mayavi based on wxPython looks ugly and feels slow and unresponsive. So back to brew and pip. After a lot of trial and error, here is what worked more or less:
1. Prerequisites
Hide/uninstall the broken Homebrew Python installation:
mv /usr/local/lib/python2.7/site-packages /usr/local/lib/python2.7/site-packages-old
mv /usr/local/share/python /usr/local/share/python-old
brew uninstall python pyqt pyside vtk
From Xcode (4.4.1), choose llvm-gcc as the compiler (I had less success with clang):
cd /usr/bin
sudo rm cc c++
sudo ln -s gcc cc
sudo ln -s g++ c++
2. Installation
2.1 Python
brew install python --framework --universal
Point to the new installation:
cd /System/Library/Frameworks/Python.framework/Versions
rm Current
ln -s /usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/Current .
If the EPD is installed, one needs to do the same in /Library/Frameworks/Python.framework/Versions, otherwise the EPD will take priority.
2.2 Numpy
Install numpy from source (pip 1.2 currently doesn't install npymath.ini correctly, which will make scipy fail to build):
git clone https://github.com/numpy/numpy.git
cd numpy
git checkout v1.6.2
python setup.py install
Since so many packages link against numpy, I really recommend checking out an official release, 1.6.2 as of today. Next make the numpy headers visible:
cd /usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/include/python2.7
ln -s /usr/local/lib/python2.7/site-packages/numpy/core/include/numpy .
2.3 qt, pyqt, vtk
Install qt (4.8.2) and pyqt (4.9.4):
brew install qt
brew install pyqt
One can also install pyside (1.1.1)
brew install pyside
but this appears to produce more crashes with mayavi. In any case, append
export QT_API=pyqt
to .bashrc to avoid any mixups. Next install vtk (5.10.0; 5.8.0 works just as well)
brew install vtk --python --tcl --examples --qt
...and wait (compilation takes around 40 minutes). The --qt flag isn't strictly necessary, but it doesn't harm either.
Next, download vtk data from http://www.vtk.org/files/release/5.10/vtkdata-5.10.0.tar.gz, unpack somewhere and have the VTK_DATA_ROOT environment variable point to the VTKData directory. Run some examples in
/usr/local/share/vtk/Examples
Launch python examples with python <example>.py and TCL examples with vtk <example.tcl>. Works absolutely beautifully, right? So let's see how mayavi messes it all up next...
2.4 ETS and mayavi
Although
pip install mayavi
gets you somewhere, it appears to produce more crashes than installing the bleeding edge from github. Get https://github.com/enthought/ets/raw/master/ets.py and run
python ets.py clone
to clone the ETS git repository. You only need apptools, mayavi, pyface, traits and traitsui, possibly envisage if you want to run mayavi2 from the command line. So delete the other directories and do
python ets.py develop
This should allow you to run some of the examples in the repository in mayavi/examples/tvtk and mayavi/examples/mayavi by running python <example>.py and play around with the GUI. There are lots of console errors and lots of GUI features that don't work, like selecting a LUT table. But it hopefully doesn't crash.
2.5 scipy, matplotlib, ipython
I prefer to get the bleeding edge from github for scipy and matplotlib. First install all dependencies using brew. Then
git clone https://github.com/scipy/scipy.git
cd scipy
python setup.py install
git clone https://github.com/matplotlib/matplotlib.git
cd matplotlib
python setup.py install
Then install ipython (0.13) using pip. For the qtconsole install first:
pip install pygments
pip install pyzmq
then
pip install ipython
There are a few possible ways to launch ipython for use with mayavi, depending on who controls the QT event loop:
ipython without mlab.show(): Hangs.
ipython with mlab.show(): Works, but prompt may become unresponsive.
ipython --gui=qt or ipython --pylab=qt: Works, but "Save" dialog closes immediately.
ipython qtconsole without mlab.show(): Hangs.
ipython qtconsole with mlab.show(): Works.
ipython qtconsole --gui=qt or ipython qtconsole --pylab=qt: Works.
Good luck!