Axes missing when plotting in matplotlib using vispy as backend - python

I have been watching the development of the python graphing library vispy with excitement. I just discovered that I can use vispy as a backend to matplotlib, which is great because I am plotting hundreds of thousands of points. I ran the example and I noticed there are no axes. I also ran the following code.
import vispy.mpl_plot as plt
plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.show()
The axes were present until the plt.show() command, and they disappeared. I understand that the vispy project is under development, but plotting with axes would be extremely valuable to me, so I was wondering how I could do this. Also, less urgently, the border around the graph becomes huge. Is there a way to shrink the border?

The support for the matplotlib backend was dropped in version 0.5:
https://github.com/vispy/vispy/pull/1224

Related

Matplotlib bbox_inches issue

I have this very simple code:
import math
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*math.pi)
fig, ax = plt.subplots()
ax.plot(x,np.sin(x))
plt.savefig('sinwave.png', bbox_inches='tight')
plt.show()
So what I would expect is that there is white background inside my plotting area, but no background around it, e.g. transparent background (only) behind the ticks and tick labels.
However, something is going wrong and it isn't working, the whole background is white. When I send it to a friend it works exactly as expected.
So I thought creating a new environment might fix it but the issue persisted. I tried it in ipython, jupyter lab and jupyter notebook, all with the same result (as to be expected but I just thought I would try). I'm using python 3.10.8 and matplotlib 3.6.2 on a Mac (2019 MacBook Pro) but it also doesn't work with other versions of python or matplotlib.
This is just a simple example but I have some 3-4 month old code which did exactly what I want back then and is now not doing it any more. Very odd.
Any ideas what might be going wrong? I really thought the new environment would fix the issue but no luck.
I'm fairly new to the community so let me know if you need any further details about my system (as it seems to be an issue with my computer/python install maybe??).
Cheers
Markus
Below are both images, you can't see the difference here as it's on white background but it's straight forward if opened e.g. in illustrator or photoshop.
fig = plt.figure()
fig.patch.set_facecolor('white')
fig.patch.set_alpha(0.6) #play with the alpha value
ax = fig.add_subplot(111)
ax.patch.set_facecolor('white')
ax.patch.set_alpha(0.0) #play with the alpha value
Then simply plot here
Plt.scatter(x,y)
Plt.show()

Incorrect backend configuration with macosx in (old) matplotlib: plt.ion different from savefig, here overwritten alpha keyword

I am using interactive python with plt.ion() for generating figures (v2.7) and have noticed that the figure looks different from the figure exported by savefig (this is not a DPI issue (cf. matplotlib savefig() plots different from show()) - I think it might be a backend issue, but would appreciate help as I don't understand this properly).
Specifically, I wanted visualise the importance of a series of points by the intensity of their colour, which I thought I could do with the "alpha" keyword in matplotlib.
When I just do this, this works fine,
but when I want to add a line to the figure, the alpha keyword seemed to not work any more, and plt.ion() shows this:
I initially thought that perhaps the following issue on github may be related:
https://github.com/matplotlib/matplotlib/issues/4580
but then I noticed that exporting the figure actually produced the following file (i.e. as desired):
It would be great to understand a bit better what is going on, and how I can avoid such issues in the future. Is plt.ion()/plt.show() not the best way to show figures in interactive python, or is this an issue with the alpha keyword?
The code is here:
import numpy as np
from numpy import random as random
from matplotlib import pyplot as plt
fig2,ax2=plt.subplots(1,1,figsize=(3,3),sharey=True)
for ii in range(1):
ax2.plot(np.linspace(0,200,200), [0.1]*200, c= 'k')
for i in range(200):
test2=random.randint(5)
ydata= random.rand(test2)
test = random.rand(test2)
for j in range(test2):
ax2.plot(i,ydata[j],'o',ms=4, c= 'Darkblue',alpha=test[j],markeredgecolor='None')

Issue with colorbar in pylab

I am trying to plot a two dimensional numpy matrix (say, Kappa) using pcolor .
The skeleton of the code is this:
from pylab import pcolor, show, colorbar, xticks, yticks
import numpy as np
plt.figure(1)
pcolor(np.transpose(Kappa))
plt.colorbar()
plt.tight_layout()
plt.show()
At the top of the colorbar, I see a weird way in which the highest scale of the colorbar is written. I have attached a picture of the the said output (and I have highlighted the troublesome part by putting it inside a red box.)
Following suggestions, I have uploaded the matrix to my Google Drive. You can use this link to access the matrix.
I am wondering if anyone has faced similar issues with colorbars in pylab? I will appreciate any help.

Matplotlib - Tcl_AsyncDelete: async handler deleted by the wrong thread?

I'm asking this question because I can't solve one problem in Python/Django (actually in pure Python it's ok) which leads to RuntimeError: tcl_asyncdelete async handler deleted by the wrong thread. This is somehow related to the way how I render matplotlib plots in Django. The way I do it is:
...
import matplotlib.pyplot as plt
...
fig = plt.figure()
...
plt.close()
I extremely minimized my code. But the catch is - even if I have just one line of code:
fig = plt.figure()
I see this RuntimeError happening. I hope I could solve the problem, If I knew the correct way of closing/cleaning/destroying plots in Python/Django.
By default matplotlib uses TK gui toolkit, when you're rendering an image without using the toolkit (i.e. into a file or a string), matplotlib still instantiates a window that doesn't get displayed, causing all kinds of problems. In order to avoid that, you should use an Agg backend. It can be activated like so --
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot
For more information please refer to matplotlib documentation -- http://matplotlib.org/faq/howto_faq.html#matplotlib-in-a-web-application-server
The above (accepted) answer is a solution in a terminal environment. If you debug in an IDE, you still might wanna use 'TkAgg' for displaying data. In order to prevent this issue, apply these two simple rules:
everytime you display your data, initiate a new fig = plt.figure()
don't close old figures manually (e.g. when using a debug mode)
Example code:
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
fig = plt.figure()
plt.plot(data[:,:,:3])
plt.show()
This proves to be the a good intermediate solution under MacOS and PyCharm IDE.
If you don't need to show plots while debugging, the following works:
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
However, if you would like to plot while debugging, you need to do 3 steps:
1.Keep backend to 'TKAgg' as follows:
import matplotlib
matplotlib.use('TKAgg')
from matplot.lib import pyplot as plt
or simply
import matplotlib.pyplot as plt
2.As Fábio also mentioned, you need to add fig(no. #i)=plt.figure(no.#i) for each figure #i. As the following example for plot no.#1, add:
fig1 = plt.figure(1)
plt.plot(yourX,yourY)
plt.show()
3.Add breakpoints. You need to add two breakpoints at least, one somewhere at the beginning of your codes (before the first plot), and the other breakpoint at a point where you would like all plots (before to the second breakpoint) are plotted. All figures are plotted and you even don't need to close any figure manually.
For me, this happened due to parallel access to data by both Matplotlib and by Tensorboard, after Tensorboard's server was running for a week straight.
Rebotting tensorboard tensorboard --logdir . --samples_per_plugin images=100 solved this for me.
I encountered this problem when plotting graphs live with matplotlib in my tkinter application.
The easiest solution I found, was to always delete subplots. I found you didn't need to instantiate a new figure, you only needed to delete the old subplot (using del subplot), then remake it.
Before plotting a new graph, make sure to delete the old subplot.
Example:
f = Figure(figsize=(5,5), dpi=100)
a = f.add_subplot(111)
(For Loop code that updates graph every 5 seconds):
del a #delete subplot
a = f.add_subplot(111) #redefine subplot
Finding this simple solution to fix this "async handler bug" was excruciatingly painful, I hope this helps someone else :)

Polar stereographic plot

Is it possible to plot contours over a polar stereographic map with the latest version of cartopy?
I'd like to see an example of how this is done as I'm struggling to work it out myself!
The stereographic projection is causing a couple of headaches and is probably the projection which has raised the most issues for cartopy's polygon transformations code.
The following example show how one should produce a polar stereographic plot with cartopy.
Please note: even with this code, it is possible to tweak the sample data resolution and find that the plot takes ~30 minutes to actually render (that is a bug which we will need to sort sooner rather than later).
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
from cartopy.examples.waves import sample_data
ax = plt.axes(projection=ccrs.NorthPolarStereo())
x, y, z = sample_data((100, 200))
cs = ax.contourf(x, y, z, 50,
transform=ccrs.PlateCarree(),
cmap='gist_ncar')
ax.coastlines()
# without the set_global, currently, the plot is tiny because the limits
# are being erroneously being set (opened issue for that)
ax.set_global()
plt.show()
Hopefully that will show you how one should make a polar stereographic contour plot in cartopy. If you having problems with your data have a look at the open issues tagged "Geometry transforms" and see if you are getting something similar, if not, go ahead and open an issue and we can look into it.
Note: This answer is relating to cartopy v0.5.x (i.e. just before a v0.5 release), and many of the bugs mentioned here should hopefully be squashed in future releases.
Hope that helps,

Categories

Resources