TclError matplotlib 1.5.0 - python

Using the code below, a TclError is generated.
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.axis([0, 6, 0, 20])
plt.show()
When I execute my script in terminal, I get the following:
/Users/<username>/anaconda/lib/python2.7/site-packages/matplotlib/__init__.py:1035: UserWarning: Duplicate key in file "/Users/<username>/.matplotlib/matplotlibrc", line #2
(fname, cnt))
objc[44479]: Class TKApplication is implemented in both /Users/<username>/anaconda/lib/libtk8.5.dylib and /System/Library/Frameworks/Tk.framework/Versions/8.5/Tk. One of the two will be used. Which one is undefined.
objc[44479]: Class TKMenu is implemented in both /Users/<username>/anaconda/lib/libtk8.5.dylib and /System/Library/Frameworks/Tk.framework/Versions/8.5/Tk. One of the two will be used. Which one is undefined.
objc[44479]: Class TKContentView is implemented in both /Users/<username>/anaconda/lib/libtk8.5.dylib and /System/Library/Frameworks/Tk.framework/Versions/8.5/Tk. One of the two will be used. Which one is undefined.
objc[44479]: Class TKWindow is implemented in both /Users/<username>/anaconda/lib/libtk8.5.dylib and /System/Library/Frameworks/Tk.framework/Versions/8.5/Tk. One of the two will be used. Which one is undefined.
2016-02-01 20:45:40.991 python[44479:21064918] setCanCycle: is deprecated. Please use setCollectionBehavior instead
2016-02-01 20:45:41.000 python[44479:21064918] setCanCycle: is deprecated. Please use setCollectionBehavior instead
Exception in Tkinter callback
Traceback (most recent call last):
File "/Users/<username>/anaconda/lib/python2.7/lib-tk/Tkinter.py", line 1536, in __call__
return self.func(*args)
File "/Users/<username>/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 283, in resize
self.show()
File "/Users/<username>/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 355, in draw
tkagg.blit(self._tkphoto, self.renderer._renderer, colormode=2)
File "/Users/<username>/anaconda/lib/python2.7/site-packages/matplotlib/backends/tkagg.py", line 30, in blit
id(data), colormode, id(bbox_array))
TclError
What is causing this error? I have tried adding backend: TkAgg to my matplotlibrc file, to no avail.
Please advise

Figured this out:
Instead of using:
matplotlib.use('TkAgg')
use:
matplotlib.use('Qt4Agg')
or any other backend

You can use 'TkAgg' but need to install Tkinter not with conda. The Anaconda packages for pil/pillow and matplotlib seem not to have TK properly included. Install pip with conda and then run pip install pillow matplotlib (Linux)
On windows you can use the packages from gohlke
http://www.lfd.uci.edu/~gohlke/pythonlibs/
install with --force-reinstall pillow matplotlib
then Tkinter TkAgg will work.

Related

Why do I get Type Error when trying to plot with matplotlib? [duplicate]

I'm new to Python. A few days ago I installed Anaconda and PyCharm (on D disk), and I am trying to use the matplotlib package to plot one picture. When I click "run", I get the following error:
Traceback (most recent call last):
File "G:\onedrive\OneDrive - mail.dlut.edu.cn\PyCharm\shock wave\P6.py", line 7, in <module>
import matplotlib.pyplot as plt
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 2230, in <module>
switch_backend(rcParams["backend"])
File "D:\anaconda3\lib\site-packages\matplotlib\__init__.py", line 672, in __getitem__
plt.switch_backend(rcsetup._auto_backend_sentinel)
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 247, in switch_backend
switch_backend(candidate)
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 267, in switch_backend
class backend_mod(matplotlib.backend_bases._Backend):
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 268, in backend_mod
locals().update(vars(importlib.import_module(backend_name)))
File "D:\anaconda3\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "D:\anaconda3\lib\site-packages\matplotlib\backends\backend_qtagg.py", line 12, in <module>
from .backend_qt import (
File "D:\anaconda3\lib\site-packages\matplotlib\backends\backend_qt.py", line 73, in <module>
_MODIFIER_KEYS = [
File "D:\anaconda3\lib\site-packages\matplotlib\backends\backend_qt.py", line 74, in <listcomp>
(_to_int(getattr(_enum("QtCore.Qt.KeyboardModifier"), mod)),
TypeError: int() argument must be a string, a bytes-like object or a number, not 'KeyboardModifier'
Process finished with exit code 1
It looks like this is a bug in pyside6 v6.3.0, one of the libraries matplotlib depends on for rendering plots; here's the bug report. It's a new bug, and it's already been fixed, so it's really bad luck that it got you!
Solution: the issue seems to be fixed in pyside version 6.4.0 (released 13 October), so one solution is to upgrade it, or you could downgrade, e.g. to version 6.2. Another solution is to try using another backend, because I think the problem only affects the Qt backend. (A backend is a rendering engine for matplotlib — read all about them.) It's easy to try this latter option, so let's start there.
Use another backend
Try this at the top of your script:
import matplotlib
matplotlib.use('tkagg')
Or you can try others; see this page for help.
Up- or down-grade pyside
To handle this, you'll need to deal with 'virtual environments'. You may already be doing this. Environments let you have different versions of Python and different collections of packages for different projects you might be working on.
Fix the base environment...
When you install Anaconda, it made an environment called base that contains 'everything' in Anaconda (Python plus lots of libraries like matplotlib). You can upgrade the version of pyside in the base environment by opening an Anaconda prompt from the Start menu and typing this:
conda install -c conda-forge pyside==6.4.0
However, most programmers don't use their base environment and prefer to manage an environment specific to their project. If you are doing this, or want to give it a try, read on.
...or make a new environment
Alternatively, to make a new environment, open an Anaconda prompt and type this but replace MYENV with a short suitable name for the environment:
conda create -n MYENV python=3.10 pyside=6.4.0 anaconda
Or you can replace anaconda with a list of the packages you want, like jupyter scipy networkx or whatever.
You would then start using this environment with conda activate MYENV and your script or notebook should run in there no problem.
Update
When Update pyside >=6.4.0, You alse need update matplotlib to 3.6.2
Reason:
Qt for Python Release: 6.4 The new Enum system
Sloution
update matplotlib to 3.6.2
Refer github Isue#24332

Importing matplotlib causes "int() argument must be a string" error

I'm new to Python. A few days ago I installed Anaconda and PyCharm (on D disk), and I am trying to use the matplotlib package to plot one picture. When I click "run", I get the following error:
Traceback (most recent call last):
File "G:\onedrive\OneDrive - mail.dlut.edu.cn\PyCharm\shock wave\P6.py", line 7, in <module>
import matplotlib.pyplot as plt
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 2230, in <module>
switch_backend(rcParams["backend"])
File "D:\anaconda3\lib\site-packages\matplotlib\__init__.py", line 672, in __getitem__
plt.switch_backend(rcsetup._auto_backend_sentinel)
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 247, in switch_backend
switch_backend(candidate)
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 267, in switch_backend
class backend_mod(matplotlib.backend_bases._Backend):
File "D:\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 268, in backend_mod
locals().update(vars(importlib.import_module(backend_name)))
File "D:\anaconda3\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "D:\anaconda3\lib\site-packages\matplotlib\backends\backend_qtagg.py", line 12, in <module>
from .backend_qt import (
File "D:\anaconda3\lib\site-packages\matplotlib\backends\backend_qt.py", line 73, in <module>
_MODIFIER_KEYS = [
File "D:\anaconda3\lib\site-packages\matplotlib\backends\backend_qt.py", line 74, in <listcomp>
(_to_int(getattr(_enum("QtCore.Qt.KeyboardModifier"), mod)),
TypeError: int() argument must be a string, a bytes-like object or a number, not 'KeyboardModifier'
Process finished with exit code 1
It looks like this is a bug in pyside6 v6.3.0, one of the libraries matplotlib depends on for rendering plots; here's the bug report. It's a new bug, and it's already been fixed, so it's really bad luck that it got you!
Solution: the issue seems to be fixed in pyside version 6.4.0 (released 13 October), so one solution is to upgrade it, or you could downgrade, e.g. to version 6.2. Another solution is to try using another backend, because I think the problem only affects the Qt backend. (A backend is a rendering engine for matplotlib — read all about them.) It's easy to try this latter option, so let's start there.
Use another backend
Try this at the top of your script:
import matplotlib
matplotlib.use('tkagg')
Or you can try others; see this page for help.
Up- or down-grade pyside
To handle this, you'll need to deal with 'virtual environments'. You may already be doing this. Environments let you have different versions of Python and different collections of packages for different projects you might be working on.
Fix the base environment...
When you install Anaconda, it made an environment called base that contains 'everything' in Anaconda (Python plus lots of libraries like matplotlib). You can upgrade the version of pyside in the base environment by opening an Anaconda prompt from the Start menu and typing this:
conda install -c conda-forge pyside==6.4.0
However, most programmers don't use their base environment and prefer to manage an environment specific to their project. If you are doing this, or want to give it a try, read on.
...or make a new environment
Alternatively, to make a new environment, open an Anaconda prompt and type this but replace MYENV with a short suitable name for the environment:
conda create -n MYENV python=3.10 pyside=6.4.0 anaconda
Or you can replace anaconda with a list of the packages you want, like jupyter scipy networkx or whatever.
You would then start using this environment with conda activate MYENV and your script or notebook should run in there no problem.
Update
When Update pyside >=6.4.0, You alse need update matplotlib to 3.6.2
Reason:
Qt for Python Release: 6.4 The new Enum system
Sloution
update matplotlib to 3.6.2
Refer github Isue#24332

CentOS Matplotlib RuntimeError: Could not open display

I am using Cuda and run into a RuntimeError.
Environment:
Python 2.7
Cuda 9.0
Torch 0.4.0
Torchvision 0.1.8
Matplotlib 1.2.0
error message:
File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_gtk.py", line 13, in <module>
import gtk; gdk = gtk.gdk
File "/usr/lib64/python2.7/site-packages/gtk-2.0/gtk/__init__.py", line 64, in <module>
_init()
File "/usr/lib64/python2.7/site-packages/gtk-2.0/gtk/__init__.py", line 52, in _init
_gtk.init_check()
RuntimeError: could not open display
Adding "MPLBACKEND=Agg" still outputs the above error message.
Anyone knows how to fix it?
I said that I would close this question. But since the answer might be interesting to some people, I leave it open. Maybe someone can explain to me why my solution worked?
I work remotely. echo $DISPLAY gives nothing. lshw -C display gives two displays. One is Nvidia's.
My problem is actually solved via adding
import matplotlib as mpl
mpl.use('Agg')
before import matplotlib.pyplot as plt.

How to use ggplot style of matplotlib with agg backend

My problem is as follows:
I have a script running remotely via a Jenkins job.
This script is making plots and saving them with plt.savefig()
Without the following line on the top of my imports, I can not run my scripts from jenkins:
matplotlib.use('Agg')
The moment I added this, I could no longer have the ggplot style on my plots:
This line:
matplotlib.style.use('ggplot')
is giving the following error:
Traceback (most recent call last):
File "plot.py", line 5, in <module>
matplotlib.style.use('ggplot')
AttributeError: 'module' object has no attribute 'style'
NOTE that:
this style was working locally when I was executing the script without the line matplotlib.use('Agg')
And the script runs normally on jenkins without the ggplot style.
How can I have both on a remote server?
(python 2.7.6, matplotlib 1.4.3)
style is a package that can be imported from matplotlib.pyplot, not directly from matplotlib.
So, try:
import matplotlib.pyplot
matplotlib.pyplot.style.use('ggplot')

matplotlib: Error in sys.exitfunc

I keep getting error in sys.exitfunc when working with matplotlib. For example, the following code throw it for matplotlib 1.3.0 / Python 2.7.3 / Ubuntu 12.04.3 LTS
from matplotlib.pyplot import figure, show
from numpy.random import random
fh = figure(figsize = (15, 10, ))
ax = fh.add_axes((.1, .1, .8, .8, ))
ax.scatter(random((100, )), random((100, )))
fh.show()
This yields
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
File "/usr/lib/python2.7/atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/_pylab_helpers.py", line 86, in destroy_all
manager.destroy()
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_gtk3.py", line 427, in destroy
self.canvas.destroy()
AttributeError: FigureManagerGTK3Agg instance has no attribute 'canvas'
Error in sys.exitfunc:
Traceback (most recent call last):
File "/usr/lib/python2.7/atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/_pylab_helpers.py", line 86, in destroy_all
manager.destroy()
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_gtk3.py", line 427, in destroy
self.canvas.destroy()
AttributeError: FigureManagerGTK3Agg instance has no attribute 'canvas'
This happens any time the program terminates without show(), including when an unrelated error is raised.
If I use show() instead of fh.show(), I don't get this error. I could just do that, but this error pops up in a lot of places and I prefer to just solve it (and I want to be able to exit without showing a figure).
I tried other backends which either are unavailable, don't have show or give the same error (this is GKT3Agg).
I had the same error. Using
matplotlib.pyplot.close()
at the end of my program fixed it. Perhaps this works for you?
plt.plot(return_array, risk_array)
plt.title('Pareto Front for '+ r'$\lambda \in$ [0.0, 1.0]')
plt.xlabel('Return')
plt.ylabel('Risk')
plt.axis([0.02, 0.05, 0.01, 0.016])
only using above code gives error but adding
matplotlib.pyplot.show()
in the end works for me
dowload matplotlib-1.3.1.tar.gz from http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.3.1/
cd matplotlib-1.3.1
sudo python setup.py install
before that install following
sudo apt-get install libfreetype6-dev
sudo apt-get install python-dev
sudo apt-get install libevent-dev
sudo apt-get install libpng-dev
I had the same error and the solution of ShikharDua solved the problem for me. My system: ubuntu 13.10 64 bit.
I wanted to run an example code which didn't call the plt.show() function at the end resulting in:
AttributeError: FigureManagerGTK3Agg instance has no attribute 'canvas'
Interestingly, the same code, without the plt.show(), worked in ipython if pylab is invoked before.
edit: Ok, i just read, that you mentioned this in your question already. So, this not really a solution for you. However, it is a solution for beginners who were wondering why some example codes don't work.
This is my horrible hack to get around it:
import matplotlib.pyplot as plt
# your use of matplotlib here where you don't use the plot.show() function
try:
plt.close()
except AttributeError, e:
pass

Categories