How to reliably convince matplotlib to use PySide2 backend when running from Anaconda (Spyder) - python-3.x

I am creating a PySide2 application which uses matplotlib. I am running this application from Spyder in an environment with PySide2 installed. This is causing the application to be run from the iPython console. Somewhere along the line, PyQt5 is imported, which I am attempting to purge in order to convince matplotlib that I really do want to use PySide2, NOT PyQt5. Something like following was working until very recently and I am not really sure why it has stopped, but safe to say this method is unreliable. How can I absolutely convince matplotlib that I am wanting PySide2?
I have tried setting the environment variable QT_API in the operating system (Windows 10), but in this case Spyder itself refuses to open.
import sys
import os
ps = list(filter(lambda x: 'PyQt5' in x, sys.modules))
for p in ps:
print(f"purging module {p}")
sys.modules.pop(p)
# matplotlib.__init__ uses this
os.environ["MPLBACKEND"] = "PySide2"
# matplotlib.backends.qt_compat uses this
os.environ["QT_API"] = "PySide2"
import PySide2.QtCore
assert "PyQt5.QtCore" not in sys.modules
assert "PySide2.QtCore" in sys.modules
# rcParams has the right idea
from matplotlib import rcParams
print(rcParams["backend"])
# qt_compat has the WRONG idea!
import matplotlib.backends.qt_compat as qt_compat
print(qt_compat.QT_API)
# The FigureCanvasWidget is of the wrong (PyQt5) type
from matplotlib.backends.backend_qt5agg import FigureCanvas
import inspect
print(inspect.getmro(FigureCanvas))

To answer this question, the reason that it stopped working was because I had set 'activate support' for Matplotlib graphics in the ipython tab under Spyder settings. After unchecking this, the above works.

Related

Vscode for python jupyter fail to show video

I'm trying to make a animation in the Jupyter of Visual Studio Code. The code is listed below.
import arviz as az
from IPython.display import HTML
from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as st
...
...
...
anim = FuncAnimation(fig, update, frames=np.arange(bins.shape[0]),
init_func=init, blit=True, interval=20)
HTML(anim.to_html5_video())
However, the Jupyter fail to play the video on the Visual Studio Code. The result was shown in the picture below.
I'm also getting this issue. I've used this animation tutorial to confirm it was an VSCode issue and not my code, which I'd confirmed works in vanilla Jupyter.
I've installed JupyterLab for use with this code sample since it's easy enough to set up.
conda install -c conda-forge jupyterlab (or pip install jupyterlab)
jupyter lab
Executing the run command from the directory with your resources with default that as the run location of Jupyter so you shouldn't need to alter your code. Here's hoping they resolve this soon.

Ubuntu Linux python plot from emacs, cannot import name '_imaging' from 'PIL'

I just got Ubuntu and I'm trying to experiment abit with emacs. Wrote a simple python code that was supposed to make a plot, but when I try to run the code I get this message;
ImportError: cannot import name '_imaging' from 'PIL' (/usr/lib/python3/dist-packages/PIL/init.py)
And also I get alot of other random stuff, but I think this is the actual error.
I generally want to run the code from the terminal window, and then get out the plot.
Here is the code:
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0,2.0,0.01)
s = 1 + np.sin(2*np.pi*t)
plt.plot(t,s)
plt.show()
I fixed the issue! Just used
pip install --upgrade --force-reinstall Pillow

ImportError: No module named 'matplotlib._path' when running a python script in apache2

I have been busting my head over this for a few hours now but I cant nail down the reason why this error occurs.
I am trying to run a simple python script in my apache2 server-
#!/usr/bin/python3.5
import cgi
import cgitb
cgitb.enable()
import sys
sys.path.insert(0, "/home/aswin/anaconda3/lib/python3.6/site-packages")
sys.path.insert(0,"/usr/local/lib/python3.5/dist-packages")
# HEADERS
print("Content-Type:text/html; charset=UTF-8")
print() # blank line required at end of headers
# CONTENT
import numpy as np
import os
# set HOME environment variable to a directory the httpd server can write to
os.environ[ 'HOME' ] = '/tmp/'
import matplotlib
# chose a non-GUI backend
matplotlib.use( 'Agg' )
import pylab
#Deals with inputing data into python from the html form
form = cgi.FieldStorage()
# construct your plot
pylab.plot([1,2,3])
print("Content-Type: image/png\n")
# save the plot as a png and output directly to webserver
pylab.savefig( sys.stdout, format='png' )
and I get the following error(screenshot attached)
I tried installing matplotlib via pip and also conda install.I also tried adding
sys.path.insert(0,"/usr/local/lib/python3.5/dist-packages") and
sys.path.insert(0, "/home/aswin/anaconda3/lib/python3.6/site-packages") as shown in the code above,
but nothing seems to fix this issue. I am running lubuntu btw.
Any help would be much appreciated. :)
screenshot of localhost
I had similar problem and it was fixed by upgrading the matplotlib

matplotlib Qt5Agg backend error: 'figure' is an unknown keyword argument

I am running python 3.5, via an up-to-date anaconda distribution, on windows 7. When I use Qt5Agg as the matplotlib backend (set via my matplotlibrc file), I get the error in the subject line. It is very simple to reproduce:
Start python from a cmd.exe prompt
from pylab import *
figure(1)
Same problem in ipython.
Thoughts? Thanks.
I had the same issue. I found the solution here
Specifically, the following now works:
import matplotlib
matplotlib.use('Qt4Agg')
from matplotlib import pyplot as plt
plt.figure(figsize=(12,8))
plt.title("Score")
plt.show()

Python 3 tkinter Photoimage "pyimage1" doesn't exist

PhotoImage: Tkinter PhotoImage objects and their idiosyncracies
http://tkinter.unpythonic.net/wiki/PhotoImage
I tested the example with python 2.7.9, 3.2.5, 3.3.5, 3.4.3 in 32bit and 64bit.
(Win 8.1 64bit)
The code works. ( even without pillow )
( in python 3.4.3 64bit I had first an error message.
I've completely uninstalled 3.4.3 and then reinstalled.
Now, the example works also with 3.4.3 64 bit )
# basic code from >>
# http://tkinter.unpythonic.net/wiki/PhotoImage
# extra code -------------------------------------------------------------------------
from __future__ import print_function
try:
import tkinter as tk
except:
import Tkinter as tk
import sys
import platform
print ()
print ('python ', sys.version)
print ('tkinter ', tk.TkVersion)
print ()
print (platform.platform(),' ',platform.machine())
print ()
# basic code -------------------------------------------------------------------------
root = tk.Tk()
def create_button_with_scoped_image():
# "w6.gif" >>
# http://www.inf-schule.de/content/software/gui/entwicklung_tkinter/bilder/w6.gif
img = tk.PhotoImage(file="w6.gif") # reference PhotoImage in local variable
button = tk.Button(root, image=img)
# button.img = img # store a reference to the image as an attribute of the widget
button.image = img # store a reference to the image as an attribute of the widget
button.grid()
create_button_with_scoped_image()
tk.mainloop()
This is done by replacing the root.Tk() by root.Toplevel()
Your script works fine for me with exactly the same version of Python 3.4 running on windows 7. I suspect the only difference is that I have also installed Pillow by downloading the wheel package from this repository. I think this includes the image support you need.
As a side note: on windows use the ttk package widgets to get buttons that actually look correct for the platform. Just import tkinter.ttk as ttk then use ttk.Button instead of tk.Button.
Update
Given the same code is working on my machine and not yours I thought I would add how I obtained this version. I installed python using chocolatey (choco install python) then added Pillow, lxml, numpy, requests and simplejson from the gohlke site.
Checking the Tk version I see that I get Tk 8.6.1 so I suspect you are picking up a Tcl/Tk installation installed locally and not shipped with your version of Python. Try ensuring no Tk installation is in your PATH and see if that resolves the problem. My output was:
python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)]
tkinter 8.6
Test Tk location:
>>> from tkinter import *
>>> root = Tk()
>>> root.eval('set tk_library')
'C:\\opt\\Python34\\tcl\\tk8.6'
I actually persuaded python to install to c:\opt\Python I think by using choco install python -ia "TARGETDIR=c:\opt\Python" but I doubt that is relevant.
You must close all open windows, which hang in the memory. If you have an error and did not destroy the window the next time you start not started there several windows. Check!

Resources