I am trying to plot data on a Cartopy grid with discrete intervals. The data ranges from 0 to 1 with a spacing of 0.05 in between. On some (seemingly random) occasions Python throws in an error saying:
IllegalArgumentException: Invalid number of points in LinearRing found 3 - must be 0 or >= 4
After this another OSError pops up (traceback is given at the end of the question). The issue is reproduced in about 70% of the time for the short example below:
V=np.arange(-1,1.05,0.05)
array_fill = np.random.random((71,361))*20//1/20
plt.figure()
ax = plt.axes(projection = ccrs.PlateCarree())
proj = ccrs.PlateCarree()
lon = np.arange(0,361)
lat = np.arange(20,91)
ax.coastlines(resolution='110m')
ax.gridlines()
ax.contourf(lon,lat,array_fill, V, cmap = cm.jet)
The randomness makes it seem to me that the error only occurs for some configurations (say, a 1 being collocated with a -1 on both sides).
One unusual aspect to this error is that it becomes less frequent when the dateline is not included (say, only plotting from 0 to 170E). When the dateline is included even for a short range (say, 170E to 170W), the error occurs with a frequency of about 70% again.
My question is: what is going wrong in the example? Or could this be an internal bug in Cartopy?
Here is the full traceback report after the initial error message:
Traceback (most recent call last):
File "C:\Program Files (x86)\Anaconda\lib\site-packages\matplotlib\backends\backend_qt5.py", line 519, in _draw_idle
self.draw()
File "C:\Program Files (x86)\Anaconda\lib\site-packages\matplotlib\backends\backend_agg.py", line 433, in draw
self.figure.draw(self.renderer)
File "C:\Program Files (x86)\Anaconda\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\Program Files (x86)\Anaconda\lib\site-packages\matplotlib\figure.py", line 1475, in draw
renderer, self, artists, self.suppressComposite)
File "C:\Program Files (x86)\Anaconda\lib\site-packages\matplotlib\image.py", line 141, in _draw_list_compositing_images
a.draw(renderer)
File "C:\Program Files (x86)\Anaconda\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\Program Files (x86)\Anaconda\lib\site-packages\cartopy\mpl\geoaxes.py", line 385, in draw
inframe=inframe)
File "C:\Program Files (x86)\Anaconda\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\Program Files (x86)\Anaconda\lib\site-packages\matplotlib\axes\_base.py", line 2607, in draw
mimage._draw_list_compositing_images(renderer, self, artists)
File "C:\Program Files (x86)\Anaconda\lib\site-packages\matplotlib\image.py", line 141, in _draw_list_compositing_images
a.draw(renderer)
File "C:\Program Files (x86)\Anaconda\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\Program Files (x86)\Anaconda\lib\site-packages\matplotlib\collections.py", line 911, in draw
Collection.draw(self, renderer)
File "C:\Program Files (x86)\Anaconda\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\Program Files (x86)\Anaconda\lib\site-packages\matplotlib\collections.py", line 266, in draw
transform, transOffset, offsets, paths = self._prepare_points()
File "C:\Program Files (x86)\Anaconda\lib\site-packages\matplotlib\collections.py", line 244, in _prepare_points
for path in paths]
File "C:\Program Files (x86)\Anaconda\lib\site-packages\matplotlib\collections.py", line 244, in <listcomp>
for path in paths]
File "C:\Program Files (x86)\Anaconda\lib\site-packages\matplotlib\transforms.py", line 2499, in transform_path_non_affine
return self._a.transform_path_non_affine(path)
File "C:\Program Files (x86)\Anaconda\lib\site-packages\cartopy\mpl\geoaxes.py", line 193, in transform_path_non_affine
geom, self.source_projection)
File "C:\Program Files (x86)\Anaconda\lib\site-packages\cartopy\crs.py", line 181, in project_geometry
return getattr(self, method_name)(geometry, src_crs)
File "C:\Program Files (x86)\Anaconda\lib\site-packages\cartopy\crs.py", line 336, in _project_polygon
return self._rings_to_multi_polygon(rings, is_ccw)
File "C:\Program Files (x86)\Anaconda\lib\site-packages\cartopy\crs.py", line 526, in _rings_to_multi_polygon
if ring.is_ccw != is_ccw:
File "C:\Program Files (x86)\Anaconda\lib\site-packages\shapely\geometry\polygon.py", line 86, in is_ccw
return bool(self.impl['is_ccw'](self))
File "C:\Program Files (x86)\Anaconda\lib\site-packages\shapely\algorithms\cga.py", line 14, in is_ccw_op
return signed_area(ring) >= 0.0
File "C:\Program Files (x86)\Anaconda\lib\site-packages\shapely\algorithms\cga.py", line 6, in signed_area
xs, ys = ring.coords.xy
File "C:\Program Files (x86)\Anaconda\lib\site-packages\shapely\geometry\base.py", line 322, in _get_coords
if self.is_empty:
File "C:\Program Files (x86)\Anaconda\lib\site-packages\shapely\geometry\base.py", line 643, in is_empty
return (self._geom is None) or bool(self.impl['is_empty'](self))
File "C:\Program Files (x86)\Anaconda\lib\site-packages\shapely\predicates.py", line 25, in __call__
return self.fn(this._geom)
OSError: exception: access violation reading 0x0000000000000000
Cartopy version is 0.16.
Thanks!
Your data for contouring must be valid for the processing. Here is the working code.
import numpy as np
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.cm as cm
V = np.arange(-1, 1.05, 0.05)
# The data must be valid for contouring
# with (*20//1/20), the data is not fine-grained enough
array_fill = np.random.random((71, 361))*2000//1/2000
plt.figure(figsize=[12,8])
ax = plt.axes(projection = ccrs.PlateCarree())
# proj = ccrs.PlateCarree()
lon = np.arange(0, 361)
lat = np.arange(20, 91)
ax.coastlines(resolution='110m', color='blue', linewidth=2)
ax.gridlines()
# (lon, lat) can't be used directly,
# meshgrid must be created from them
xs, ys = np.meshgrid(lon, lat)
ax.contourf(xs, ys, array_fill, V, cmap = cm.jet)
plt.show()
The resulting image:
Related
I am trying to save an eps file using savefig method of matplotlib, but I am getting an unusual exception (KeyError), and the message isn't actionable. Let me know what can be done thanks.
Regards,
Harsh
data_for_x_axis = [0,30,60,90,120,150,180]
data_for_y_axis = [0, 0.1, 0.2, 0.3, 0.2, 0.1, 0]
AX1 = plt.subplot(221)
plt.margins(1)
AX1.cla()
AX1.plot(data_for_x_axis, data_for_y_axis) # some data
AX1.set_xlim([0,180])
AX1.set_xticks([0,30,60,90,120,150,180])
AX1.set_yticks([0.5,1])
AX1.set_title(r'Normalized Stokes $I$')
AX1.set_xlabel('CQWP Rotation Angle (Degrees)')
AX1.set_ylabel(r'$I/I_{mean}$')
plt.savefig('.\\Plots\\4_ModDemod.eps', format='eps', dpi=2400)
This throws the following exception
xception in Tkinter callback
Traceback (most recent call last):
File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/backends/_backend_tk.py", line 256, in resize
self._tkcanvas.create_image(
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/backends/backend_tkagg.py", line 9, in draw
super(FigureCanvasTkAgg, self).draw()
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py", line 388, in draw
self.figure.draw(self.renderer)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/figure.py", line 1709, in draw
renderer, self, artists, self.suppressComposite)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/image.py", line 135, in _draw_list_compositing_images
a.draw(renderer)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/axes/_base.py", line 2605, in draw
artists.remove(spine)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/axes/_base.py", line 2554, in _update_title_position
# this happens for an empty bb
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/text.py", line 890, in get_window_extent
bbox, info, descent = self._get_layout(self._renderer)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/text.py", line 298, in _get_layout
clean_line, self._fontproperties, ismath=ismath)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py", line 206, in get_text_width_height_descent
self.mathtext_parser.parse(s, self.dpi, prop)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/mathtext.py", line 3362, in parse
font_output = fontset_class(prop, backend)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/mathtext.py", line 883, in __init__
self.cm_fallback = StixSansFonts(*args, **kwargs)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/mathtext.py", line 984, in __init__
fullpath = findfont(name)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/font_manager.py", line 1238, in findfont
rc_params)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/font_manager.py", line 1270, in _findfont_cached
+ self.score_size(prop.get_size(), font.size))
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/font_manager.py", line 1151, in score_weight
w1 = weight1 if isinstance(weight1, Number) else weight_dict[weight1]
KeyError: '1'
I am recently working on making auto07p work with matplotlib 2.0.
The source code can be found here:
https://sourceforge.net/projects/auto-07p/files/auto07p/0.9/
When using matplotlib 2.0 (or any version greater than 1.5), IndexError: invalid index to scalar variable. appears:
/home/ngb/auto/07p/python/Points.py:1086: VisibleDeprecationWarning: `rank` is deprecated; use the `ndim` attribute or function instead. To find the rank of a matrix see `numpy.linalg.matrix_rank`.
r = rank(array_temp)
Created plot
<graphics.windowPlotter.WindowPlotter2D object at 0x7f9e42007710>
AUTO> Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.5/tkinter/__init__.py", line 1562, in __call__
return self.func(*args)
File "/usr/lib/python3.5/tkinter/__init__.py", line 608, in callit
func(*args)
File "/usr/lib/python3/dist-packages/matplotlib/backends/backend_tkagg.py", line 370, in idle_draw
self.draw()
File "/home/ngb/auto/07p/python/graphics/grapher_mpl.py", line 92, in draw
self.redraw()
File "/home/ngb/auto/07p/python/graphics/grapher_mpl.py", line 65, in redraw
FigureCanvasTkAgg.draw(self)
File "/usr/lib/python3/dist-packages/matplotlib/backends/backend_tkagg.py", line 351, in draw
FigureCanvasAgg.draw(self)
File "/usr/lib/python3/dist-packages/matplotlib/backends/backend_agg.py", line 464, in draw
self.figure.draw(self.renderer)
File "/usr/lib/python3/dist-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/python3/dist-packages/matplotlib/figure.py", line 1143, in draw
renderer, self, dsu, self.suppressComposite)
File "/usr/lib/python3/dist-packages/matplotlib/image.py", line 139, in _draw_list_compositing_images
a.draw(renderer)
File "/usr/lib/python3/dist-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/python3/dist-packages/matplotlib/axes/_base.py", line 2409, in draw
mimage._draw_list_compositing_images(renderer, self, dsu)
File "/usr/lib/python3/dist-packages/matplotlib/image.py", line 139, in _draw_list_compositing_images
a.draw(renderer)
File "/usr/lib/python3/dist-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/python3/dist-packages/matplotlib/axis.py", line 1136, in draw
ticks_to_draw = self._update_ticks(renderer)
File "/usr/lib/python3/dist-packages/matplotlib/axis.py", line 969, in _update_ticks
tick_tups = [t for t in self.iter_ticks()]
File "/usr/lib/python3/dist-packages/matplotlib/axis.py", line 969, in <listcomp>
tick_tups = [t for t in self.iter_ticks()]
File "/usr/lib/python3/dist-packages/matplotlib/axis.py", line 912, in iter_ticks
majorLocs = self.major.locator()
File "/usr/lib/python3/dist-packages/matplotlib/ticker.py", line 1794, in __call__
return self.tick_values(vmin, vmax)
File "/usr/lib/python3/dist-packages/matplotlib/ticker.py", line 1802, in tick_values
locs = self._raw_ticks(vmin, vmax)
File "/usr/lib/python3/dist-packages/matplotlib/ticker.py", line 1761, in _raw_ticks
istep = np.nonzero(steps >= raw_step)[0][0]
IndexError: invalid index to scalar variable.
It appears that there are only two lines involved. They are from the file /auto/07p/python/graphics/grapher_mpl.py.
The two methods involved are:
def redraw(self):
# recalculate label positions
self.grapher.plotlabels()
FigureCanvasTkAgg.draw(self)
And
def draw(self):
ax = self.grapher.ax
d = {}
if ax is self.grapher.ax3d:
[d["minx"], d["maxx"]] = ax.get_xlim3d()
[d["miny"], d["maxy"]] = ax.get_ylim3d()
[d["minz"], d["maxz"]] = ax.get_zlim3d()
d["azimuth"] = ax.azim
d["elevation"] = ax.elev
d["cur_lims"] = Axes.get_xlim(ax), Axes.get_ylim(ax)
else:
[d["minx"], d["maxx"]] = ax.get_xlim()
[d["miny"], d["maxy"]] = ax.get_ylim()
for k in list(d):
# don't adjust any unchanged settings
if k == "cur_lims":
if map(list, d[k]) == map(list, self.grapher._cur_lims):
del d[k]
elif d[k] == self.grapher.cget(k):
del d[k]
if d != {}:
if "cur_lims" in d:
del d["cur_lims"]
if d != {}:
self.grapher._configNoDraw(**d)
self.redraw()
return
FigureCanvasTkAgg.draw(self)
I would appreciate if anyone can assist me with the error, without changing the matlibplot code but only the auto code. I have read through the code but did not find anything suspicious.
I ran into this error using a given equation and auto file. But if you use matplotlib 2.0 and auto07p to plot most graphs in general, you are very likely to get this error if you zoom on the graph.
I used the files as the following:
https://1drv.ms/f/s!ArJqyyCr1FQOhkITst8JdVK_mIFV
Put them in auto folder.
Run auto.
and type:
auto("couple2.auto")
Thanks.
I'm trying to plot with seaborn.kdeplot with LaTeX labels. What I tried is the following:
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(font_scale=1.5, rc={'text.usetex' : True})
x = np.linspace(-50,50,100)
y = np.sin(x)**2/x
fig = plt.figure(1)
sns.set_style('white')
sns.kdeplot(np.array(y), label='hey')
fig.gca().set(xlabel=r'$e(t_0)$ [s]', ylabel='PDF')
fig.savefig("seaborntest.png", close = True, verbose = True)
Running this I've got the following error:
Traceback (most recent call last):
File "./sns_problem.py", line 17, in <module>
fig.savefig("seaborntest.png", close = True, verbose = True)
File "/usr/lib64/python2.7/site-packages/matplotlib/figure.py", line 1363, in savefig
self.canvas.print_figure(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/matplotlib/backend_bases.py", line 2093, in print_figure
**kwargs)
File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 491, in print_png
FigureCanvasAgg.draw(self)
File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 439, in draw
self.figure.draw(self.renderer)
File "/usr/lib64/python2.7/site-packages/matplotlib/artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib64/python2.7/site-packages/matplotlib/figure.py", line 999, in draw
func(*args)
File "/usr/lib64/python2.7/site-packages/matplotlib/artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib64/python2.7/site-packages/matplotlib/axes.py", line 2086, in draw
a.draw(renderer)
File "/usr/lib64/python2.7/site-packages/matplotlib/artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib64/python2.7/site-packages/matplotlib/axis.py", line 1050, in draw
renderer)
File "/usr/lib64/python2.7/site-packages/matplotlib/axis.py", line 999, in _get_tick_bboxes
extent = tick.label1.get_window_extent(renderer)
File "/usr/lib64/python2.7/site-packages/matplotlib/text.py", line 752, in get_window_extent
bbox, info = self._get_layout(self._renderer)
File "/usr/lib64/python2.7/site-packages/matplotlib/text.py", line 304, in _get_layout
ismath=False)
File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 196, in get_text_width_height_descent
texmanager = self.get_texmanager()
File "/usr/lib64/python2.7/site-packages/matplotlib/backend_bases.py", line 597, in get_texmanager
self._texmanager = TexManager()
File "/usr/lib64/python2.7/site-packages/matplotlib/texmanager.py", line 137, in __init__
ff = rcParams['font.family'].lower()
AttributeError: 'list' object has no attribute 'lower'
What could be the problem? The strange thing is that I got this error even if I remove the line adding the labels. What is the proper way of using LaTeX in seaborn plot labels?
If you do not have latex install on your machine, this could be causing errors.
For Linux users try installing Latex:
sudo apt update
sudo apt-get install texlive-latex-extra texlive-fonts-recommended dvipng cm-super
If in notebook, restart the Kernel, and then the font should display using Latex.
So I have a lot of images that I am plotting for data quality control purposes. I am using nested loops to go through and extract the gzipped files and then plot and save the images as .png so they can later be referred to. I can get it to run for a while but eventually I will get a Memory Error. I don't know if I am making a dumb mistake, any help is appreciated.
I have tried making temp folders to extract the gzipped files to and then removing them. I have also tried closing all the plots after I make them each time in the loop, however I still get a memory error after running it for a while. I did some googling and an issue with flushing and fsync, as well as the fact that the gzipped files are on a NTFS formatted external hard drive, but that is where I get lost.
Below is the my relevant code:
while len(thelist) > 0 :
temppath = tempfile.mkdtemp()
os.chdir(temppath)
tpath = thelist.pop()
myextractor.myextract(tpath)
paths = glob('*HRV')+glob('*.IR120')+glob('*.WV73')+glob('*.VIS8')+glob('*.VIS120')+glob('*.VIS6')+glob('*.IR16')
for x in range(0, len(paths)):
#get the files and paths correct
spath ='/' + paths.__getitem__(x)
spath1 = spath.replace('\\','/')
spath = temppath+ spath1
spath = spath.replace('\\','/')
r = 0
r=McIdasObject.McIdasImageFile(spath)
#the semi colon is important ..maybe
fig = plt.imshow (np.array(r));
#most of this is just getting the correct file and path name
strpath = str(temppath)
strpath = strpath.replace('c:\\users\\appdata\\local\\temp\\','/')
folder = tpath[20]+tpath[21]+tpath[22]+tpath[23]+tpath[24]+tpath[25]+tpath[26]+tpath[27]+tpath[28]
newpath = savepath + '/' + folder
if not os.path.exists(newpath): os.makedirs(newpath)
print 'saving:' + newpath + spath1 + '.png'
plt.savefig(newpath + spath1+ '.png')
r=0
plt.close("all")
gc.collect()
os.chdir(destin)
if len(paths) < 1 :
badimages.append(temppath)
else:
shutil.rmtree(temppath)
This is the trace back
Traceback (most recent call last):
File "<ipython-input-1-22dce83b27e3>", line 1, in <module>
runfile('C:/Users/Alex/Documents/Python Scripts/image printer.py', wdir='C:/Users/Alex/Documents/Python Scripts')
File "C:\Users\Alex\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 682, in runfile
execfile(filename, namespace)
File "C:\Users\Alex\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 71, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "C:/Users/Alex/Documents/Python Scripts/image printer.py", line 57, in <module>
plt.savefig(newpath + spath1+ '.png')
File "C:\Users\Alex\Anaconda\lib\site-packages\matplotlib\pyplot.py", line 577, in savefig
res = fig.savefig(*args, **kwargs)
File "C:\Users\Alex\Anaconda\lib\site-packages\matplotlib\figure.py", line 1476, in savefig
self.canvas.print_figure(*args, **kwargs)
File "C:\Users\Alex\Anaconda\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 161, in print_figure
FigureCanvasAgg.print_figure(self, *args, **kwargs)
File "C:\Users\Alex\Anaconda\lib\site-packages\matplotlib\backend_bases.py", line 2211, in print_figure
**kwargs)
File "C:\Users\Alex\Anaconda\lib\site-packages\matplotlib\backends\backend_agg.py", line 521, in print_png
FigureCanvasAgg.draw(self)
File "C:\Users\Alex\Anaconda\lib\site-packages\matplotlib\backends\backend_agg.py", line 469, in draw
self.figure.draw(self.renderer)
File "C:\Users\Alex\Anaconda\lib\site-packages\matplotlib\artist.py", line 59, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Users\Alex\Anaconda\lib\site-packages\matplotlib\figure.py", line 1085, in draw
func(*args)
File "C:\Users\Alex\Anaconda\lib\site-packages\matplotlib\artist.py", line 59, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Users\Alex\Anaconda\lib\site-packages\matplotlib\axes\_base.py", line 2110, in draw
a.draw(renderer)
File "C:\Users\Alex\Anaconda\lib\site-packages\matplotlib\artist.py", line 59, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Users\Alex\Anaconda\lib\site-packages\matplotlib\image.py", line 373, in draw
im = self.make_image(renderer.get_image_magnification())
File "C:\Users\Alex\Anaconda\lib\site-packages\matplotlib\image.py", line 597, in make_image
transformed_viewLim)
File "C:\Users\Alex\Anaconda\lib\site-packages\matplotlib\image.py", line 219, in _get_unsampled_image
x = (x * 255).astype(np.uint8)
MemoryError
Here's a simple example that's the same as your problem. On my machine, this causes ipython to use up all the memory and then crash:
import matplotlib.pyplot as plt
import numpy as np
for ii in np.arange(1000):
fig = plt.imshow(np.random.random([1000,1000]))
(Next time, if you can figure it out, try to provide an example like this that's as small as possible, removing all nonessential code).
Rather than recreating a figure every time, try creating the figure once and re-using it:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.imshow(np.random.random([1000,1000]))
for ii in np.arange(1000):
fig.set_data(np.random.random([1000,1000]))
Just wanted to see if others thought that the following behaviour in matplotlib plot_date was buggy, or if it's just something I should put up with.
I have a multi-panel plot that I set up with sharex to facilitate zoom/pan on all axes, and I plot time series data in both panels. However, in the second panel, all of the data happens to be invalid (in this example I mask it).
from matplotlib.pyplot import figure,show
from datetime import datetime,timedelta
from numpy import sin,cos,linspace,pi,ma,array
fig=figure(figsize=(16,9))
ax1=fig.add_subplot(211)
ax2=fig.add_subplot(212,sharex=ax1)
# xdata is seconds
xdata=linspace(0,9999,10000)
tdata=array([datetime(2000,1,1)+timedelta(seconds=ss) for ss in xdata])
data1=ma.masked_array(sin(pi*xdata/300),mask=False)
data2=ma.masked_array(cos(pi*xdata/300),mask=True)
ax1.plot_date(tdata,data1,marker='',color='r')
ax2.plot_date(tdata,data2,marker='',color='b')
show()
I'd expect (prefer) it to just show up a blank panel, not to fail and give me a long unhelpful traceback. Is this the expected behaviour?
Notes:
This script also fails if I use ax.plot(...) instead of ax.plot_date(...)
It works fine (i.e. gives me an empty panel) if I just plot against xdata, not the datetime array tsdata (but I have to use ax1.set_xlim(xdata[0],xdata[-1]) to get a sensible domain displayed):
ax1.plot(xdata,data1,marker='',color='r')
ax2.plot(xdata,data2,marker='',color='b')
ax1.set_xlim(xdata[0],xdata[-1])
show()
I have just realised I can rescue the above plot by forcing the ax2 limits right before the show() command. I still think that the failure in the main example is inelegant:
ax2.set_xlim(tdata[0],tdata[-1])
show()
What do the experts think?
Thanks!
F.Y.I., This was on matplotlib 1.1.0, compiled from source on my PC.
Here is the traceback that I get:
Traceback (most recent call last):
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/backendsbackend_gtk.py", line 395, in expose_even
self._render_figure(self._pixmap, w, h)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/backends/backend_gtkagg.py", line 75, in _render_f
FigureCanvasAgg.draw(self)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 401, in draw
self.figure.draw(self.renderer)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/figure.py", line 884, in draw
func(*args)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/axes.py", line 1983, in draw
a.draw(renderer)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/axis.py", line 1036, in draw
ticks_to_draw = self._update_ticks(renderer)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/axis.py", line 926, in _update_ticks
tick_tups = [ t for t in self.iter_ticks()]
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/axis.py", line 873, in iter_ticks
majorLocs = self.major.locator()
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/dates.py", line 749, in __call__
self.refresh()
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/dates.py", line 758, in refresh
dmin, dmax = self.viewlim_to_dt()
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/dates.py", line 530, in viewlim_to_dt
return num2date(vmin, self.tz), num2date(vmax, self.tz)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/dates.py", line 289, in num2date
if not cbook.iterable(x): return _from_ordinalf(x, tz)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/dates.py", line 203, in _from_ordinalf
dt = datetime.datetime.fromordinal(ix)
ValueError: ordinal must be >= 1
If you suspect this is an IPython bug, please report it at:
https://github.com/ipython/ipython/issues
or send an email to the mailing list at ipython-dev#scipy.org
Yes, I would call this a bug, or at least an oversight which looks like it has been fixed (via #ali_m https://github.com/matplotlib/matplotlib/issues/162).
I was getting this exception, but that was on a version of 1.3.x from June (my bad, thought I had a more current version on this computer). Current master does not have this problem and #ali_m reports that it also works on 1.2.1 and 1.3.0 so I suspect the fix is to upgrade you version of matplotlib.
What looks like is going on is that there isn't a check in the code that sorts out where to put the ticks has no check to make sure you have given in non-empty data.
The reason that setting the limits explicitly prevents the error is that the code never tries to figure out what the range of your empty data is.
Please create a github issue for this (and include the trace back in the issue).
In [7]: Traceback (most recent call last):
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/backends/backend_qt4.py", line 366, in idle_draw
self.draw()
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/backends/backend_qt4agg.py", line 148, in draw
FigureCanvasAgg.draw(self)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/backends/backend_agg.py", line 440, in draw
self.figure.draw(self.renderer)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/figure.py", line 1027, in draw
func(*args)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/axes.py", line 2088, in draw
a.draw(renderer)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/axis.py", line 1076, in draw
ticks_to_draw = self._update_ticks(renderer)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/axis.py", line 938, in _update_ticks
tick_tups = [t for t in self.iter_ticks()]
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/axis.py", line 882, in iter_ticks
majorLocs = self.major.locator()
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/dates.py", line 785, in __call__
self.refresh()
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/dates.py", line 794, in refresh
dmin, dmax = self.viewlim_to_dt()
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/dates.py", line 560, in viewlim_to_dt
return num2date(vmin, self.tz), num2date(vmax, self.tz)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/dates.py", line 305, in num2date
return _from_ordinalf(x, tz)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/dates.py", line 208, in _from_ordinalf
dt = datetime.datetime.fromordinal(ix)
ValueError: ordinal must be >= 1