Matplotlib: Customizing Qt4Agg Backend - python

I am trying to customize the Qt4Agg backend. To ensure that I didn't insert any bugs, as a starting point, I copied matplotlib/backends/backend_qt4agg.py to a new location on my PYTHONPATH, renamed it "my_backend.py", and corrected two import statements as follows:
from backend_agg import ...
from backend_qt4 import ...
becomes
from matplotlib.backends.backend_agg import ...
from matplotlib.backends.backend_qt4 import ...
In my matplotlib RC file I changed the backend to module://my_backend.py.
When plotting from a script using "show()", everything works as normal. But when trying to execute within an ipython session started with "ipython --pylab", the figure shows up, but nothing ever plots and I get a spinning wheel. How can I fix this?
I am using OSX Mavericks, Python 2.7.3, IPython 1.1.0, and Matplotlib 1.3.1.
Thanks

The problem occurs because the GUI main loop fails to start because IPython does not recognize the backend, and therefore, it doesn't know which GUI to use. This can be remedied by manually starting the GUI main loop in an IPython startup file. In ~/.ipython/profile_default/startup/my_backend_start_gui.py I placed the following code:
import matplotlib
if matplotlib.rcParams['backend'] == 'module://my_backend':
from IPython.lib.inputhook import enable_gui
enable_gui('qt4')
Now everything works fine.

Related

How do I change the backend in CoCalc to show a matplotlib scatter graph?

I have a program that is working fine locally, but I need to use it in CoCalc on the cloud to share with a group. Everything works fine until the end, when I want to create a scatter graph, in standard way. There are a bunch of other specs, but essentially, it's just
plt.scatter(x, y, color = 'blue')
plt.show()
Nothing tricky. But in Cocalc, it tells me "UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure."
Here are the imports from the beginning of the file:
import nltk
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
I've searched for this error and tried the solutions I've found, such as importing tkinter. So, for instance, if I change the headers to
import nltk
import tkinter as tk
import pandas as pd
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np
I get a different error: "Cannot load backend 'TkAgg' which requires the 'tk' interactive framework, as 'headless' is currently running."
I've seen instructions about pip installations and such, but a) I'm not sure the installations would make everything work for my group, and b) CoCalc generally has most of the standard packages ready to go, so maybe that's not the problem?
Obviously, I'm not experienced with these issues, so help is much appreciated.
If you're using a Jupyter notebook in CoCalc, then the above will just work fine. Here's an example:
https://cocalc.com/wstein/support/matplotlib-scatter-in-jupyter
If you're writing all of your code as part of a Python program (so, e.g., .py files) and running this from a Terminal, CoCalc will also fully support Tk and this working! However, you have to start a new X11 desktop session in CoCalc by clicking +New --> "Linux Graphical X11 Desktop", then run your Python program from the terminal in the upper left. You'll see any windows that pop up in the main window off to the right.
See https://cocalc.com/wstein/support/scatter-matplotlib-x11

How to change the default backend in matplotlib from 'QtAgg' to 'Qt5Agg' in Pycharm?

Qt5Agg is necessary to use the mayavi 3D visualization package. I have installed PyQt5 and mayavi using pip in a separate copied conda environment. The default backend then changes from TkAgg to QtAgg. This is a bit weird because in an earlier installation in a different PC the default changed directly to Qt5Agg. I always check the backend using the following commands from the python console :
import matplotlib
matplotlib.get_backend()
Even with the backend being 'QtAgg', I am able to use mayavi from the terminal without any issue but not when I do so in Pycharm. Here I get a non-responsive empty window (image below) :
Image of the non-responsive window
I have been able to get rid of this issue by explicitly using Qt5Agg instead of QtAgg before the plt call :
import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
But I would prefer a better way than using the above in every script that I write. As I had mentioned earlier, I already have mayavi installed and have used it successfully it in Pycharm in a different PC and there the default backend is 'Qt5Agg' and hence there is no need to change the backend explicitly.
Is there anything obvious that I'm overlooking ? Can you please let me know of a way to change the default backend for matplotlib from QtAgg to Qt5Agg after PyQt5 installation using pip ?
Thanks in advance !!
Thanks to #PaulH's comment, I was able to solve the issue. Owing to #mx0's suggestion, I shall now explicitly mention the fix below so that others can also benefit from it.
In a particular conda environment, if matplotlib package is installed, then there will be a 'matplotlibrc' file stored somewhere that defines what the default backend will be whenever matplotlib is imported from that conda environment. The location of this 'matplotlibrc' can be found using the following commands :
import matplotlib
matplotlib.matplotlib_fname()
Please look into the following link if there's any deprecation issue with the above commands :
https://matplotlib.org/stable/tutorials/introductory/customizing.html#customizing-with-matplotlibrc-files
Once the location of the 'matplotlibrc' file is known, open it and simply uncomment one line inside this file. Just change the backend from :
##backend: Agg
to :
backend: Qt5Agg
And that's it. All the plot window troubles in PyCharm will be solved as far as the mayavi 3D visualization package is concerned. For any other use, where a specific backend is necessary, you can also set the default to any other backend of choice.

How can I display an image on VS Code and PyCharm?

I want to choose the best IDE for Python programming so I'm testing different softwares but I have problem.
When I try this code blocks on VS Code I don't see any error but the image is not showing
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
image = mpimg.imread('exit-ramp.jpg')
plt.imshow(image)
VS Code
When I try run the same code on PyCharm I see some errors
PyCharm
But when I run the same code on Jupyter Notebook it works. What can I do?
Bro, try that:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
image = mpimg.imread('exit-ramp.jpg')
plt.imshow(image)
plt.show()
i've made a test in my vscode.
Few weeks ago i used a lot pycharm... but i get some library errors with pandas and pycharm its a little bit heavy.
VSCODE its light and i didnt get any library error that i had with pycharm.
I believe this is a backend problem to be changed in matplotlib. If you start your Python shell whether you are in a bash shell or in vscode, you should use a backend that will show the plot. Otherwise the plt.show() call is required.
So, one solution is to change the backend either manually in you Python shell or when starting the Python shell as explained here below.
Note, however, that I always use the qt5 backend but got the same issue as yours: no plot appears. I changed to the Qt5Agg backend and it worked for me (providing PyQt5 is installed).
So, first solution, you can try to set the backend when starting the Python shell:
ipython --pylab Qt5Agg
You should use a GUI backend amongst the possible backend. If you do not known, try to replace Qt5Agg by auto
The second solution consists in changing the backend manually once in the Python shell:
import matplotlib as plt
plt.use('Qt5Agg')
Right click on your code -> Run current file in interactive window.

%matplotlib inline doesn't work on iPython and Jupyter console

I'm trying out Jupyter console for the first time, but can't get the %matplotlib inline magic to work. Below is a screenshot of an example session:
The plot shows in a separate window after I run Line 6, and Line 7 doesn't do anything.
When I run %matplotlib --list, inline is given as one of the options:
Available matplotlib backends: ['osx', 'qt4', 'qt5', 'gtk3', 'notebook', 'wx', 'qt',
'nbagg', 'agg', 'gtk', 'tk', 'ipympl', 'inline']
When I try to use another backend, say qt5, it gives an error message because I don't have any Qt installed.
ImportError: Matplotlib qt-based backends require an external PyQt4, PyQt5, or PySide
package to be installed, but it was not found.
Running %matplotlib?? reads:
If you are using the inline matplotlib backend in the IPython Notebook
you can set which figure formats are enabled using the following::
In [1]: from IPython.display import set_matplotlib_formats
In [2]: set_matplotlib_formats('pdf', 'svg')
The default for inline figures sets `bbox_inches` to 'tight'. This can
cause discrepancies between the displayed image and the identical
image created using `savefig`. This behavior can be disabled using the
`%config` magic::
In [3]: %config InlineBackend.print_figure_kwargs = {'bbox_inches':None}
But I don't know if it's something I can tweak around to solve my issue.
When I try it the magic IPython console, it says inline is an Unknown Backend.
UnknownBackend: No event loop integration for u'inline'. Supported event loops are: qt,
qt4, qt5, gtk, gtk2, gtk3, tk, wx, pyglet, glut, osx
I've also found this issue on github after some googling but I don't even know if it's relevant to my situation (most of their conversation didn't make sense to me lol).
Lastly, I'm not sure if this issue is related at all, but here it is, just in case: when I try to open Vim in Jupyter via the !vim command, it glitches pretty badly, preventing me from even exiting out of Jupyter itself without closing the terminal altogther. Vim works perfectly fine when called inside IPython console, however.
I'm using matplotlib 2.0.0.
If anyone could help me figure this out, that'd be great! Thank you!
You’re running a console which is completely text based and incapable of showing images. Therefore, although inline is available, it's not producing inline output.
I'm not sure why it doesn't throw an error, though, which it does in my case:
You can use %matplotlib inline in a GUI console, like Jupyter QTConsole
or in a jupyter notebook in the browser
%matplotlib without the inline works for me (I'm using osx and IPython 7.0.1)
If you're running an old version of ipython try %pylab inline instead. See notes in this tutorial

How do I display a matplotlib figure window on top of all other windows in Spyder

I am using the Spyder IDE and I find that matplotlib figure windows always get displayed behind other windows. For example, immediately after starting Spyder, if I type plt.plot([0,1],[0,1]) in the console, I get a plot behind the main Spyder window. How can I make new figure windows display on top off all other windows?
I found this solution (make matplotlib plotting window pop up as the active one), but it does not work for me in Spyder. I run into trouble with fig.canvas.manager.window. It says AttributeError: 'FigureManagerMac' object has no attribute 'window'.
Well, I happened upon the solution when I was working on something else.
When I use the MacOSX backend, then fig.canvas.manager.window gives AttributeError: 'FigureManagerMac' object has no attribute 'window'. However, when I use the TkAgg backend, then fig.canvas.manager has the attribute window. Thus, I can implement this suggestion as follows:
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot([0,1],[0,1])
#Put figure window on top of all other windows
fig.canvas.manager.window.attributes('-topmost', 1)
#After placing figure window on top, allow other windows to be on top of it later
fig.canvas.manager.window.attributes('-topmost', 0)
Simple enough, right? The first tricky part is you must set the backend before you import pyplot. Changing the backend afterwards does nothing in my experience. The second tricky part is Spyder's Scientific Startup script does import matplotlib.pyplot as plt right when you launch the Spyder IDE, so you have no chance to set the backend before pyplot is imported. The way around this is go to Preferences->Console->External Modules, set the GUI Backend to TkAgg, and restart Spyder. Then the code above works properly.
Previously I was setting the backend via matplotlib.rcParams['backend'] = 'TkAgg' right after launching Spyder. When I was doing something else, however, I started getting errors that mentioned the MacOSX backend. This did not make any sense to me, since I thought I was using TkAgg. The maddening part is when I queried matplotlib.get_backend it returned TkAgg! Apparently, setting the backend after importing pyplot acts as if you have changed the backend, but it does not actually change the backend. Argg!!

Categories