Why does my plot freeze/not show in matplotlib outside of Spyder - python

So I have the following code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import colors
plt.ion()
example_data = np.random.randint(5, size=(44,80))
cmap = colors.ListedColormap(['black','white','green','blue','red'])
bounds = [0,1,2,3,4,5]
norm = colors.BoundaryNorm(bounds, cmap.N)
img = plt.imshow(example_data, interpolation='nearest',origin='lower',cmap=cmap, norm=norm)
plt.draw()
If I run this with the backend in matplotlibrc set to Qt4Agg, I get the plot appearing but the window is 'Not responding' and needs to be forced to close.
If I run it with the backend set to GTK3Agg (Which is what I'm aiming for really) I get a blank plot window with no plot on it and the message 'python.exe has stopped working'
If I run it within Spyder then it all works fine (Backend is Qt4Agg here I think). I get exactly what I want and no freezing/unresponsiveness.
Could anyone help? I think I'm not fully understanding the interactive issues with running it outside of the IDE.
Thanks.
EDIT:
Error log is:
Traceback (most recent call last)
File"<string>", line 73, in execInThread
File"<string>", line 44, in __call__
File"C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\netref.py", line 196, in __call__
File"C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\netref.py", line 71, in syncerq
File"C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\protocol.py", line 431, in sync_request
File"C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\protocol.py", line 379, in serve
File"C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\protocol.py", line 337, in _recv
File"C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\channel.py", line 50, in recv
File"C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\stream.py", line 166, in read
EOFError: [WinError 10054] An existing connection was forcibly closed by the remote host
EDIT2:
So looking in the Windows Event viewer logs I can see I get:
ERROR - APPLICATION ERROR:
Faulting Application name:python.exe, version 0.0.0.0, time stamp: 0x54f9ed12
Faulting module name: libcairo-2.dll, version 0.0.0.0, time stamp 0x50a184bb
Exception code: 0xc0000005
Fault offset: 0x00023024
Faulting process id: 0xca8
Faulting application start time: 0x01d1f7a6ba424ee5
Faulting application path: C:\Anaconda3\python.exe
Faulting module path: C:\Anaconda3\Lib\site-packages\GTK+-Bundle-3.6.1\bin\libcairo-2.dll
Report Id: ff7c449c-6399-11e6-ba70-0cc47a6a54fd
So maybe it's something to do with the libcairo-2.dll? I reinstalled GTK to see if that helped but appears to have made no difference.

In PyScripter 2.7.10 in menu Run-> Python engine -> Internal.

Related

Adafruit MAX 31856 communicating with raspberrypi

I have been trying to read a thermocouple temperature on my raspberrypi however cant get the raspi to communicate with the adafruit MAX 31856. I have downloaded necessary libraries and checked that all connections are secure and correct however keep running into this error when I try to execute this code.
Any help is greatly appreciated!!
CODE
import board
import digitalio
import adafruit_max31856
spi = board.SPI()
cs = digitalio.DigitalInOut(board.D5)
cs.direction = digitalio.Direction.OTUPUT
thermocouple = adafruit_max31856.MAX31856(spi,cs)
print(thermocouple.temperature)
ERROR:
Traceback (most recent call last):
File "/home/pi/test4.py", line 6, in <module>
spi = board.SPI()
File "/usr/local/lib/python3.7/dist-packages/board.py", line 299, in SPI
return busio.SPI(SCLK, MOSI, MISO)
File "/usr/local/lib/python3.7/dist-packages/busio.py", line 289, in __init__
self._spi = _SPI(portId)
File "/usr/local/lib/python3.7/dist-packages/adafruit_blinka/microcontroller/generic_linux/spi.py", line 25, in __init__
self._spi = spi.SPI(device=(portid, 0))
File "/usr/local/lib/python3.7/dist-packages/Adafruit_PureIO/spi.py", line 167, in __init__
raise IOError("{} does not exist".format(device))
OSError: /dev/spidev0.0 does not exist
Code
Errors
Most probably there is a device driver loaded for spi0-0 and that removes /dev/spidev0.0 device.
check your /boot/config.txt for overlays loading MAX 31856 driver module.
if you want to use adafruit_max31856 lib you shouldn't be loading this driver. hope that helps

Python stopped working after the first instance of "Segmentation fault (core dumped)" error message upon executing some previously valid code

Today, I noticed that my python code while executing, produces the following upon execution without actually execute the code:
Segmentation fault (core dumped)
After checking out this page (Error: Segmentation fault (core dumped)), I noticed that my python has actually crashed rather than something else.
Here is the error message first I received before my later attempts resulting in the above error message (This is not reproducible and I was lucky to save it somewhere):
Traceback (most recent call last):
File "my_code.py", line 984, in <module>
cf = ax12.tricontourf(x, y, z, levels, cmap=cm.get_cmap(cmap, len(levels)-1), norm=norm)
File "/home/username/anaconda3/lib/python3.6/site-packages/matplotlib/axes/_axes.py", line 8025, in tricontourf
return mtri.tricontourf(self, *args, **kwargs)
File "/home/username/anaconda3/lib/python3.6/site-packages/matplotlib/tri/tricontour.py", line 282, in tricontourf
return TriContourSet(ax, *args, **kwargs)
File "/home/username/anaconda3/lib/python3.6/site-packages/matplotlib/tri/tricontour.py", line 40, in __init__
ContourSet.__init__(self, ax, *args, **kwargs)
File "/home/username/anaconda3/lib/python3.6/site-packages/matplotlib/contour.py", line 846, in __init__
kwargs = self._process_args(*args, **kwargs)
File "/home/username/anaconda3/lib/python3.6/site-packages/matplotlib/tri/tricontour.py", line 51, in _process_args
tri, z = self._contour_args(args, kwargs)
File "/home/username/anaconda3/lib/python3.6/site-packages/matplotlib/tri/tricontour.py", line 85, in _contour_args
**kwargs)
File "/home/username/anaconda3/lib/python3.6/site-packages/matplotlib/tri/triangulation.py", line 164, in get_from_args_and_kwargs
triangulation = Triangulation(x, y, triangles, mask)
File "/home/username/anaconda3/lib/python3.6/site-packages/matplotlib/tri/triangulation.py", line 55, in __init__
self.triangles, self._neighbors = _qhull.delaunay(x, y)
RuntimeError: Error in qhull Delaunay triangulation calculation: precision error (exitcode=3); use python verbose option (-v) to see original qhull error.
By the way, I am using python3 from anaconda on an Ubuntu linux. Is there any way to narrow down the issue by downgrading to some previous versions of python? However, it doesn't seem that python itself has been upgraded recently after checking it through:
conda info python
Thanks,
Are you using virtualenv? You can sometimes get weird errors running Python in virtualenv after updating System Python, usually a segfault or dynamic linking errors. From what I understand this happens because the python executable inside the virtualenv is of different version than the libpython.so that it's trying to load from the system. To work around this issue, you will need to recreate the virtualenv.

Matplotlib graph not showing

My project requires me to open Raspberry Pi's terminal using putty and Connectify hotspot on my Windows System to plot and show the graph. However , the graph was only able to be shown on my Raspberry Pi monitor but not my Window's one. Here's the code that i used :
import pymysql
import matplotlib
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
conn = pymysql.connect(host="localhost", user="root", passwd="123456", db="XXX")
cur = conn.cursor()
query = """
SELECT data,time
FROM sensordata
WHERE time >= "2017-05-21"
AND time < "2017-05-23"
"""
cur.execute(query)
data = cur.fetchall()
cur.close()
conn.close()
time,data= zip(*data)
plt.plot(data,time)
plt.title("XXX ")
plt.xlabel("Time & Date ")
plt.ylabel("Strength")
fig = plt.gcf()
fig.set_size_inches (55,27.5)
plt.grid(True)
plt.draw()
fig.savefig('test.png' ,dpi=100)
plt.show()
The error i received when i tried to run it on the putty terminal is :
Traceback (most recent call last):
File "matplot2.py", line 27, in <module>
plt.plot(data,time)
File "/usr/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 3092, in plot
ax = gca()
File "/usr/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 828, in gca
ax = gcf().gca(**kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 462, in gcf
return figure()
File "/usr/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 435, in figure
**kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib/backends/backend_tkagg.py", line 81, in new_figure_manager
return new_figure_manager_given_figure(num, figure)
File "/usr/lib/python2.7/dist-packages/matplotlib/backends/backend_tkagg.py", line 89, in new_figure_manager_given_figure
window = Tk.Tk()
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1813, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
I've tried using both matplotlib.use('Agg') and matplotlib.use('TKAgg') from some solutions i read but it did not solve my issue. Hope that someone would be able to solve my issue so that i can display the graph on my Window's monitor ... Thanks in advance
The error '_tkinter.TclError: no display name and no $DISPLAY environment variable' suggests that there is a problem with your X11 server.
I do not know from which host you ssh on your Raspberry, but you must run an X-Server on Windows (such as VcXsrv ). Then make sure to allow X11 forwarding, e.g. ssh -X or even ssh -Y. When using putty make sure to set Enable X11 forwarding under Connection -> SSH -> X11.
If all is set up, running the matplotlib bar chart demo (see comments) should look like this:
enter image description here
(no image since someone downvoted the answer for whatever reason)
If your problem persists, you could try to use MobaXTerm (on Windows) which comes with an X Server and should work out of the box.
If you are running VcXSrv, for me I have to export my $DISPLAY variable by running the following code in your shell: export DISPLAY=localhost:0.0

RuntimeError: Invalid DISPLAY variable

I am running my python script in another machine by using ssh command in linux. I have also run this command :
source ~/.bashrc
after logging in the other machine, in order to define the proper paths in the new machine. I was getting the error message for running the following python code lines even I have tried to follow the instruction in this question by defining the backend.
>>> import matplotlib
>>> import pylab as plt
>>> matplotlib.use('Agg')
>>> import numpy as np
>>> x=np.arange(0,2,0.001)
>>> y=np.sin(x)**2+4*np.cos(x)
>>> fig = plt.figure()
>>> plt.plot(x,y,'r.')
The error message
This probably means that Tcl wasn't installed properly.
Traceback (most recent call last):
File "Systematic_Optimised.py", line 513, in <module>
fig = plt.figure()
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.py", line 435, in figure
**kwargs)
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4agg.py", line 47, in new_figure_manager
return new_figure_manager_given_figure(num, thisFig)
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4agg.py", line 54, in new_figure_manager_given_figure
canvas = FigureCanvasQTAgg(figure)
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4agg.py", line 72, in __init__
FigureCanvasQT.__init__(self, figure)
File "/vol/aibn84/data2/zahra/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4.py", line 68, in __init__
_create_qApp()
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt5.py", line 138, in _create_qApp
raise RuntimeError('Invalid DISPLAY variable')
RuntimeError: Invalid DISPLAY variable
any suggestion how to fix the problem
You must declare matplotlib.use('agg') before import pylab as plt.
Reference
Add
plt.switch_backend('agg')
after
import matplotlib.pyplot as plt

bundle_files = 1 fails with py2exe using matplotlib

I am trying to create a standalone application using py2exe that depends on matplotlib and numpy. The code of the application is this:
import numpy as np
import pylab as plt
plt.figure()
a = np.random.random((16,16))
plt.imshow(a,interpolation='nearest')
plt.show()
The setup code for py2exe (modified from http://www.py2exe.org/index.cgi/MatPlotLib) is this:
from distutils.core import setup
import py2exe
import sys
sys.argv.append('py2exe')
opts = {
'py2exe': {"bundle_files" : 3,
"includes" : [ "matplotlib.backends",
"matplotlib.backends.backend_qt4agg",
"pylab", "numpy",
"matplotlib.backends.backend_tkagg"],
'excludes': ['_gtkagg', '_tkagg', '_agg2',
'_cairo', '_cocoaagg',
'_fltkagg', '_gtk', '_gtkcairo', ],
'dll_excludes': ['libgdk-win32-2.0-0.dll',
'libgobject-2.0-0.dll']
}
}
setup(console=[{"script" : "matplotlib_test.py"}],
zipfile=None,options=opts)
Now, when bundle_files is set = 3 or is absent, all works fine, but the resulting exe cannot be distributed to a machine that is not configured with the same version of Python, etc. If I set bundle_files = 1, it creates a suitably large exe file that must have everything bundled, but it fails to run locally or distributed. In this case, I'm creating everything on a Windows 7 machine with Python 2.6.6 and trying to run locally and on an XP machine with Python 2.6.4 installed.
The errors I get when running on the XP machine seem strange since, without bundling, I get no errors on Win 7. With bundling, Win 7 does not report the traceback information, so I cannot be sure the errors are the same. In any case, here's the error message on XP:
Traceback (most recent call last):
File "matplotlib_test.py", line 2, in <module>
File "zipextimporter.pyc", line 82, in load_module
File "pylab.pyc", line 1, in <module>
File "zipextimporter.pyc", line 82, in load_module
File "matplotlib\__init__.pyc", line 709, in <module>
File "matplotlib\__init__.pyc", line 627, in rc_params
File "matplotlib\__init__.pyc", line 565, in matplotlib_fname
File "matplotlib\__init__.pyc", line 240, in wrapper
File "matplotlib\__init__.pyc", line 439, in _get_configdir
RuntimeError: Failed to create C:\Documents and Settings\mnfienen/.matplotlib; c
onsider setting MPLCONFIGDIR to a writable directory for matplotlib configuratio
n data
Many thanks in advance if anyone can point me in a direction that will fix this!
EDIT 1:
I followed William's advice and fixed the problem with MPLCONFIGDIR, but now get a new error:
:Traceback (most recent call last):
File "matplotlib\__init__.pyc", line 479, in _get_data_path
RuntimeError: Could not find the matplotlib data files
EDIT 2:
I fixed the data files problem by using:
data_files=matplotlib.get_py2exe_datafiles()
This leads to a new error:
Traceback (most recent call last):
File "matplotlib_test.py", line 5, in <module>
import matplotlib.pyplot as plt
File "matplotlib\pyplot.pyc", line 78, in <module>
File "matplotlib\backends\__init__.pyc", line 25, in pylab_setup
ImportError: No module named backend_wxagg
I had the same problem. I think the problem was caused by pylab in matplotlib, py2exe seemed to have trouble finding and getting all the backends associated with pylab.
I got around the problem by changing all my embedded plots to use matplotlib.figure instead of pylab. Here's a simple example on how to make a plot with matplotlib.figure:
import matplotlib.figure as fg
import numpy as np
fig = fg.Figure()
ax = fig.add_subplot(111)
lines = ax.plot(range(10), np.random.randn(10), range(10), np.random.randn(10))
You cannot use fig.show() directly with this, but it can be embedded in GUIs. I used Tkinker:
canvas = FigureCanvasTkAgg(fig, canvas_master)
canvas.show()
Well Misha Fienen, I guess it seems to be failing to write to your user folder, which you probably already knew. Just a stab in the dark but have you tried testing what happens if you follow the advice and change MPLCONFIGDIR to something a bit more basic (eg. "C:\matlibplotcfg\")?
There are two ways of solving the problem.
1.- In your matplotlib.rc file use:
backend : TkAgg
2.- alternatively, in your setup.py "includes" key add:
"matplotlib.backends.backend_wxagg"
both ways produce the test figure in Python 2.6, windows XP

Categories

Resources