Fatal Python error: GC object already tracked - python

I use matplotlib to create some charts, using the AGG backend.
import matplotlib
matplotlib.use('AGG')
import matplotlib.plot as plt
# ...
def chart_view(request):
fig = plt.figure
# Do stuff with fig and finally save it in a Django HttpResponse
# object and return the HttpResponse object.
Now I have a web page that has three images, all three images resulting in running chart_view. Only one image usually makes it, and the Django development server stops with "Fatal Python error: GC object already tracked". I'm not certain the problem is in matplotlib, it could be in pandas.
How can I debug the problem?

OK, I found out that it's doing it when I use Debian Jessie's matplotlib 1.4.2 in combination with the latest pandas (0.17.0) that I have installed with pip install --upgrade --no-deps pandas (in a virtualenv that uses --system-site-packages). If I use Debian's pandas 0.14.1 everything's fine. Go figure why this is. Anyway, using Debian's packages is what I intended to do so this solves the problem for me.

Related

How to fix Object of type ndarray is not JSON serializable while using mpld3?

Python mpld3 '.show()' Gives me this error "Object of type ndarray is not JSON serializable"
I know that there are many duplicates of this question here, however, I haven't been able to find a recent one. This seems to be a common problem with mpld3.
Using Matplotlib version 3.1.3
Using mpld3 version 0.3
I'm also using Anaconda and did a conda upgrade --all and a conda update --all and still get this error.
Here is some code to reproduce the error. [It's really simple]
import matplotlib.pyplot as plt
import mpld3
fig, ax = plt.subplots()
x, y = [[1,2,3],[4,3,2]]
ax.scatter(x, y)
mpld3.show()
Any idea on a quick fix? Or if someone more knowing than I, could post this somewhere where it can be addressed appropriately?
The code above is just a bare bones example to show that there are no numpy arrays being used in the plot creation itself. It is no way a representation of what I'm trying to do [Show a matplotlib figure on a webpage in a simple way]. I know that matplotlib uses numpy internally, so it must be some issue with mpld3 parsing the figure properties dictionary.
I had the same issue as you and I was able to reproduce with your code.
I was just testing a fresh installed mpld3 when I encountered this error.
What I did to fix it is to uninstall mpld3 (which I had installed with pip) and re-install it with conda.
Then it worked.
Checking version with conda list gives me the same versions of both package as you have.
I remember reading that one should not play with both pip and conda for python package managing. I always forget to apply to this rule.
Hope it will fix it for you.

matplotlib example code not working on python virtual environment

I am trying to display the x y z coordinate of an image in matplotlib. the example code work perfectly well on the global python installation: As I move the cursor the x,y,z values get updated instantaneously. However, when I run the example code on a python virtual environment, I would click on the images several times for the coordinate to show in the first place, then when I click on different positions it would update for some. After few clicks, the coordinates will no longer update.
I don't know how to debug this.
This is likely to be a problem with the macosx backend for matplotlib. Switch to using an alternative backend for matplotlib (e.g. use qt4 instead of 'macosx'). For details of how to switch backend and what exactly that means - see the docs here. Note that you might have to install the backend first - e.g. pyqt to use the qt4agg backend as I'm suggesting here.
In summary - the backend deals with the output from matplotlib and matplotlib can target different output formats. These can be gui display output formats (for instance wx, qt4 and so on), or file outputs (for instance pdf). These are known as interactive and non-interactive backends respectively.
To change backend either do
import matplotlib
matplotlib.use('qt4agg')
in code, or - if you want to change for every time you start matplotlib - edit your matplotlibrc file setting the backend attribute e.g.
backend: Qt4Agg
N.B. I was alerted by a comment that since posting this answer, matplotlib docs now refer to this issue and suggest a workaround, although the commenter noted that the solution offered in this answer (switch to Qt backend) worked for them where the official docs workaround was not possible for them.
What finally worked for me was to make a local matplotlibrc file containing the directive: backend: TkAgg.
# Within working directory where running python
vim matplotlibrc
# new file via vim, Nano, whatever
backend: TkAgg
This was useful:
import matplotlib
print matplotlib.rcParams['backend']
Other Notes:
I had also installed pyqt using Homebrew (brew install pyqt) and copied (could just move it) into $MyVirtEnv/lib/python2.7/site-packages/ from /usr/local/lib/python2.7/site-packages/PyQt4
But when I
import matplotlib
matplotlib.use('qt4Agg')
import librosa
"Matplotlib qt-based backends require an external PyQt4, PyQt5,\n"
ImportError: Matplotlib qt-based backends require an external PyQt4, PyQt5,
or PySide package to be installed, but it was not found.
Had also tried
pip install pyside
Successfully installed pyside-1.2.4
Same error
>>> import pyside
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named pyside
Also got the following error at some point when trying to reimport matplotlib (i think).
from . import cache
ImportError: cannot import name cache
As pointed out in Matplotlib virtualenv FAQ, vext is the solution here.
It allows to use the system-wide pyqt5 for instance.
This is necessary until PyQt5 setup knows about virtualenvs:
pip3 install vext.pyqt5
Just add plt.show() at the end and the problem was solved for me.

Matplotlib Basemap not working Windows 8.1

I want to plot some GPS-data using python 2.7 using matplotlibs basemap.
I download the binary windows installer and it executes and run without any problems. However, when I try to import and run in python I get:
from mpl_toolkits.basemap import basemap
ImportError: No module named basemap
I tried the
python setup.py
and
pip install basemap-1.0.8-cp27-none-win_amd64
in prompt which seems to be succesful.
GEOS, which is a dependency should be involved in the Basemap installer but I installed OSGeo4w64 separately to make sure geos_c and init is in place.
I hope someone can help me out. This feels like it is well above my level.
I have ofcourse looked through other threads on this page, but none of them seem to offer a solution.
Best regards
Instead of this:
from mpl_toolkits.basemap import basemap
do this:
from mpl_toolkits.basemap import Basemap
Check this as well.

plot window doesn't show - Tkinter present but header files are not found.

I have an application in python2.7 which runs fine.
Because i wanted to run it on a different laptop,i installed the matplotlib1.1 .
The problem is that the application finishes but no plot window exists.
Problem with Gtk or Tk? I tried to do in the matplotlibrc file "backend:TkAgg" or "GtkAgg" but still the same.
I forgot to mention that the laptop runs linux.
----------EDIT-------------------
I tried the installation again and it shows a message:
You may need to define display for tk to work so that setup can
determine where your libraries are located.Tkinter present but header
files are not found.
Some part of code:
import matplotlib.pyplot as plt
import scipy as sc
from matplotlib.animation import ArtistAnimation
...........
fig=plt.gcf()
ani=ArtistAnimation(fig,result,interval=10,repeat=False)
plt.show()
Even with TkAgg, matplotlib does not necessarily show the plot until you explicitly tell it to.
If you use pylab, you can explicitly cause it to show with something like this:
import pylab
pylab.plot([1,2,1,3])
pylab.show()
The call to show() will return when you close the window.
You can make it automatically show when you do a plot by writing
interactive: true
in your matplolibrc file. There is a system-wide config file in mpl-data/matplotlibrc in the installed packate. You have a personal config in ~/.matplotlib/matplotlibrc
Some systems seem to have interactive=true by default, others do not.
I found the answer here.
Finally!
(I have done manual install because it wanted the version 1.1)
I tried this :
sudo apt-get install python-pip
sudo pip install matplotlib

matplotlib does not show my plot although I call pyplot.show()

Help required on matplotlib. Yes, I did not forget calling the pyplot.show().
$ ipython --pylab
import matplotlib.pyplot as p
p.plot(range(20), range(20))
It returns matplotlib.lines.Line2D at 0xade2b2c as the output.
p.show()
There is nothing to happen. No error message. No new window. Nothing. I install matplotlib by using pip and I didn't take any error messages.
Details:
I use,
Ubuntu
IPython v0.11
Python v2.6.6
matplotlib v1.0.1
If I set my backend to template in ~/.matplotlib/matplotlibrc,
then I can reproduce your symptoms:
~/.matplotlib/matplotlibrc:
# backend : GtkAgg
backend : template
Note that the file matplotlibrc may not be in directory ~/.matplotlib/. In this case, the following code shows where it is:
>>> import matplotlib
>>> matplotlib.matplotlib_fname()
In [1]: import matplotlib.pyplot as p
In [2]: p.plot(range(20),range(20))
Out[2]: [<matplotlib.lines.Line2D object at 0xa64932c>]
In [3]: p.show()
If you edit ~/.matplotlib/matplotlibrc and change the backend to something like GtkAgg, you should see a plot. You can list all the backends available on your machine with
import matplotlib.rcsetup as rcsetup
print(rcsetup.all_backends)
It should return a list like:
['GTK', 'GTKAgg', 'GTKCairo', 'FltkAgg', 'MacOSX', 'QtAgg', 'Qt4Agg',
'TkAgg', 'WX', 'WXAgg', 'CocoaAgg', 'agg', 'cairo', 'emf', 'gdk', 'pdf',
'ps', 'svg', 'template']
Reference:
Customizing matplotlib
I ran into the exact same problem on Ubuntu 12.04, because I installed matplotlib (within a virtualenv) using
pip install matplotlib
To make long story short, my advice is: don't try to install matplotlib using pip or by hand; let a real package manager (e.g. apt-get / synaptic) install it and all its dependencies for you.
Unfortunately, matplotlib's backends (alternative methods for actually rendering your plots) have all sorts of dependencies that pip will not deal with. Even worse, it fails silently; that is, pip install matplotlib appears to install matplotlib successfully. But when you try to use it (e.g. pyplot.show()), no plot window will appear. I tried all the different backends that people on the web suggest (Qt4Agg, GTK, etc.), and they all failed (i.e. when I tried to import matplotlib.pyplot, I get ImportError because it's trying to import some dependency that's missing). I then researched how to install those dependencies, but it just made me want to give up using pip (within virtualenv) as a viable installation solution for any package that has non-Python package dependencies.
The whole experience sent me crawling back to apt-get / synaptic (i.e. the Ubuntu package manager) to install software like matplotlib. That worked perfectly. Of course, that means you can only install into your system directories, no virtualenv goodness, and you are stuck with the versions that Ubuntu distributes, which may be way behind the current version...
%matplotlib inline
For me working with notebook, adding the above line before the plot works.
Just type:
plt.ion()
See https://www.youtube.com/watch?v=1zmV8lZsHF4 at 23:30 !
plt is used because of my import: import matplotlib.pyplot as plt
I'm using python2.7 on a mac with iTerm2.
For future reference,
I have encountered the same problem -- pylab was not showing under ipython. The problem was fixed by changing ipython's config file {ipython_config.py}. In the config file
c.InteractiveShellApp.pylab = 'auto'
I changed 'auto' to 'qt' and now I see graphs
What solved my problem was just using the below two lines in ipython notebook at the top
%matplotib inline
%pylab inline
And it worked. I'm using Ubuntu16.04 and ipython-5.1
Adding the following two lines before importing pylab seems to work for me
import matplotlib
matplotlib.use("gtk")
import sys
import pylab
import numpy as np
I had to install matplotlib from source to get this to work. The key instructions (from http://www.pyimagesearch.com/2015/08/24/resolved-matplotlib-figures-not-showing-up-or-displaying/) are:
$ workon plotting
$ pip uninstall matplotlib
$ git clone https://github.com/matplotlib/matplotlib.git
$ cd matplotlib
$ python setup.py install
By changing the backend, as #unutbu says, I just ran into loads more problems with all the different backends not working either.
Similar to #Rikki, I solved this problem by upgrading matplotlib with pip install matplotlib --upgrade. If you can't upgrade uninstalling and reinstalling may work.
pip uninstall matplotlib
pip install matplotlib
Be sure to have this startup script enabled :
( Preferences > Console > Advanced Options )
/usr/lib/python2.7/dist-packages/spyderlib/scientific_startup.py
If the standard PYTHONSTARTUP is enabled you won't have an interactive plot
For me the problem happens if I simply create an empty matplotlibrc file under ~/.matplotlib on macOS. Adding "backend: macosx" in it fixes the problem.
I think it is a bug: if backend is not specified in my matplotlibrc it should take the default value.
After running your code include:
import pylab as p
p.show()
if you are a nube from ruby, don't forget the parenthesis - show()
If you are working with yolov5 the fixes described here might not work as in my case. YOLOv5 developers have turned off the preview of the images using plt.show(), so most likely this will happen to you. To resolve make sure that your environment is correctly configured using requirements.txt file that comes with yolov5 and then use the workaround:
import torch
import matplotlib
model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # Load model first
matplotlib.use('TkAgg') # Change backend after loading model
as described here: https://github.com/ultralytics/yolov5/issues/2779
you can also try another backend from the ones mentioned above like 'Qt4Agg' or smth else.
I found that I needed window = Tk() and then window.mainloop()
It also shows the error when you don't call plt.plot() on anything. I got that error haha. I though I was calling it in a loop but right before the loop I overwrote my array to a blank array so it never entered the loop
For Ubuntu 12.04:
sudo apt-get install python-qt4
virtualenv .env --no-site-packages
source .env/bin/activate
easy_install -U distribute
ln -s /usr/lib/python2.7/dist-packages/PyQt4 .
ln -s /usr/lib/python2.7/dist-packages/sip.so .
pip install matplotlib

Categories

Resources