Memory Error when plotting images using loops python - python

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]))

Related

pandas causing NoneType error in matplotlib plt.savefig() and plt.show()?

I want to read a csv file using the read_csv method, and then plot the data using matplotlib. However, I cannot seem to create a simple matplotlib plot (even without using the data from the file), after I use pandas to read in some csv data. It gives the error: 'NoneType' object is not callable.
Any idea what's going on here?
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("data.csv")
time = [0,10,20]
vel = [0,1,2]
fig,axes = plt.subplots()
axes.plot(time,vel)
plt.show()
plt.savefig(fname = "pic.png" )
I have tried using plot.savefig instead of plot.show() and this produces the same error.
If I move the plotting block of code before the pd.read_csv line, it plots just fine. The error only seems to occur after pandas is used.
This is occuring in Visual Studio. Not occuring in IDLE.
Traceback:
Traceback (most recent call last):
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\numpy\core\getlimits.py", line 384, in __new__
dtype = numeric.dtype(dtype)
TypeError: 'NoneType' object is not callable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\backends\backend_qt.py", line 455, in _draw_idle
self.draw()
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\backends\backend_agg.py", line 436, in draw
self.figure.draw(self.renderer)
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\artist.py", line 73, in draw_wrapper
result = draw(artist, renderer, *args, **kwargs)
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\artist.py", line 50, in draw_wrapper
return draw(artist, renderer)
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\figure.py", line 2803, in draw
mimage._draw_list_compositing_images(
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\image.py", line 132, in _draw_list_compositing_images
a.draw(renderer)
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\artist.py", line 50, in draw_wrapper
return draw(artist, renderer)
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\axes\_base.py", line 3020, in draw
self._unstale_viewLim()
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\axes\_base.py", line 776, in _unstale_viewLim
self.autoscale_view(**{f"scale{name}": scale
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\axes\_base.py", line 2932, in autoscale_view
handle_single_axis(
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\axes\_base.py", line 2895, in handle_single_axis
x0, x1 = locator.nonsingular(x0, x1)
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\ticker.py", line 1654, in nonsingular
return mtransforms.nonsingular(v0, v1, expander=.05)
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\transforms.py", line 2880, in nonsingular
if maxabsvalue < (1e6 / tiny) * np.finfo(float).tiny:
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\numpy\core\getlimits.py", line 387, in __new__
dtype = numeric.dtype(type(dtype))
TypeError: 'NoneType' object is not callable

Matplotlib running out of memory

I am having two problems, both related to memory problems. The first case happens when there are about 5 resolvers used (see code and explanation below), the second when there are used about 15 resolvers. To the first problem there is a similar question on Stackoverflow. The solution to this problem was to clear the memory after each loop but I want to create mutliple datalines in a single graph, so this doesn't work for me.
Here is the code snippet where all that happens:
fig = plt.figure()
ax = fig.add_subplot(111)
def add_plot(resolver_name, results):
sum_results = sum(results)
norm = [float(i)/sum_results for i in results]
cy = np.cumsum(norm)
ax.plot(results, cy, label=resolver_name, linewidth=0.8)
for resolver in resolvers:
results = db.get_rt(resolver["ipv4"], tls)
add_plot(resolver["name"], results)
# Positioning of legend
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
fig.set_size_inches(10,5)
ax.set_xscale('log')
plt.title('CDF response time for '+('DNS-over-TLS measurements' if tls else 'DNS measurements'))
plt.xlabel("Response time (ms)")
plt.ylabel("CDF")
plt.grid(True)
png_name = V.base_directory+"/plots/rt_cdf.png"
if (tls):
png_name = V.base_directory+"/plots/rt_cdf_tls.png"
log.info("Plotting graph to "+png_name)
plt.savefig(png_name)
The variable resolvers contains some information about several public DNS resolvers. The variable results is a list of float values. All other unclear variables should not be relevant to this problem. But feel free to ask if you need further explanation.
Problem 1
As said this happens when there are used about 5 resolvers. The size of results varies between ~1 million and ~6 million entries. A MemoryError occurs at the last line:
Traceback (most recent call last):
File "plot_building/rt_cdf.py", line 63, in <module>
plt.savefig(png_name)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 695, in savefig
res = fig.savefig(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/figure.py", line 2062, in savefig
self.canvas.print_figure(fname, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backend_bases.py", line 2263, in print_figure
**kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_agg.py", line 517, in print_png
FigureCanvasAgg.draw(self)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_agg.py", line 437, in draw
self.figure.draw(self.renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/figure.py", line 1493, in draw
renderer, self, artists, self.suppressComposite)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/image.py", line 141, in _draw_list_compositing_images
a.draw(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_base.py", line 2635, in draw
mimage._draw_list_compositing_images(renderer, self, artists)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/image.py", line 141, in _draw_list_compositing_images
a.draw(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/lines.py", line 756, in draw
tpath, affine = (self._get_transformed_path()
File "/usr/local/lib/python2.7/dist-packages/matplotlib/transforms.py", line 2848, in get_transformed_path_and_affine
self._revalidate()
File "/usr/local/lib/python2.7/dist-packages/matplotlib/transforms.py", line 2822, in _revalidate
self._transform.transform_path_non_affine(self._path)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/transforms.py", line 2492, in transform_path_non_affine
return self._a.transform_path_non_affine(path)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/transforms.py", line 1564, in transform_path_non_affine
x = self.transform_non_affine(path.vertices)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/transforms.py", line 2271, in transform_non_affine
return np.concatenate((x_points, y_points), 1)
MemoryError
Problem 2
This was a bit harder to figure out. At some point during the runtime the process just stopped. After some searching I found the following in var/log/syslog
[27578124.494907] Out of memory: Kill process 376 (python) score 897 or sacrifice child
[27578124.495020] Killed process 376 (python) total-vm:2081432kB, anon-rss:1833416kB, file-rss:1464kB
I think some other lines in the logfile might also belong to this problem but what I've found is that this problem is caused by having not enough RAM.
The script is running on a Ubuntu VM with 2GB RAM.
Any ideas how I could fix any of those problems?
Are you watching your system monitor whilst running this? Are you running out of RAM?
6 million points seems huge can you not just sample less?

Setting the linestyle for the longitude and latitude lines in matplotlib's Basemap?

I am using maplotlib's Basemap to draw maps of the world and want to include longitude and latitude lines. This can be done using drawmeridians() and drawparallels(), but the linestyle of the corresponding lines can only be set via the keyword dashes. According to the documentation, see see here, is should work as follows:
dash pattern for meridians (default [1,1], i.e. 1 pixel on, 1 pixel off)
I tried dashes=[1,0] but that did not worked. Is there any simple way to have solid linestyle?
Here is my code:
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.basemap import Basemap
fig1, ax1 = plt.subplots(1,1)
map1 = Basemap( resolution='l', projection='mill',
llcrnrlat=-60., llcrnrlon=-180.,
urcrnrlat=90., urcrnrlon=180. )
map1.drawcoastlines()
map1.drawmapboundary( fill_color='aqua' )
map1.fillcontinents( color='coral', lake_color='aqua' )
# labels=[left,right,top,bottom]
map1.drawparallels( np.arange(-80.,81.,20.), labels=[True,True,False,False] )
map1.drawmeridians( np.arange(-180.,181.,40.), labels=[False,False,True,True] )
plt.show()
Here is the resulting map:
Edit 1: I just tried on a different computer and there it works, i.e. dashes=[1,0] results in solid linestyle. The version used on that computer are (according to a pip freeze)
basemap==1.2.0
matplotlib==2.2.3
As soon as I have access again to the original computer, I'll check what is going on there (and which versions are installed).
Edit 2: Being back at the computer where it did not worked, I can now tell a bit more. First, the following versions are used:
basemap==1.1.1
matplotlib==3.0.2
Then the error message (which I forgot to include previously):
ValueError: All values in the dash list must be positive
Edit 3: For the sake of completeness (and since it was partly helpful to hunt down the solution), here is the full Traceback:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1540, in __call__
return self.func(*args)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_tkagg.py", line 280, in resize
self.show()
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_tkagg.py", line 351, in draw
FigureCanvasAgg.draw(self)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_agg.py", line 464, in draw
self.figure.draw(self.renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/figure.py", line 1143, in draw
renderer, self, dsu, self.suppressComposite)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/image.py", line 139, in _draw_list_compositing_images
a.draw(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_base.py", line 2409, in draw
mimage._draw_list_compositing_images(renderer, self, dsu)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/image.py", line 139, in _draw_list_compositing_images
a.draw(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/lines.py", line 822, in draw
drawFunc(renderer, gc, tpath, affine.frozen())
File "/usr/local/lib/python2.7/dist-packages/matplotlib/lines.py", line 1267, in _draw_lines
self._lineFunc(renderer, gc, path, trans)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/lines.py", line 1297, in _draw_dashed
gc.set_dashes(self._dashOffset, self._dashSeq)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backend_bases.py", line 1007, in set_dashes
raise ValueError("All values in the dash list must be positive")
After some research on some bugreports on github I found the solution [1], dashes=(None,None):
map1.drawmeridians( np.arange(-180.,181.,40.), labels=[False,False,True,True], dashes=(None,None) )
[1] https://github.com/matplotlib/basemap/issues/173#issuecomment-68243710

an error in python plot

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.linear_model import LinearRegression
a = np.zeros((1000,3))
fig=plt.figure()
ax=fig.gca(projection='3d')
line1,=ax.plot(a[:,0], a[:,1], a[:,2], 'k')
ax.set_xlabel('$x_1_t$');ax.set_ylabel('$x_1_t-tau$');ax.set_zlabel('$x_1_t-2tau$')
plt.title('hello')
plt.show()
I use python2.x. The error message is the following. Anyone knows how to fix it?
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backends/backend_macosx.py", line 83, in _draw
self.figure.draw(renderer)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/figure.py", line 1475, in draw
renderer, self, artists, self.suppressComposite)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/image.py", line 141, in _draw_list_compositing_images
a.draw(renderer)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 298, in draw
ax.draw(renderer)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axis3d.py", line 306, in draw
self.label.draw(renderer)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/text.py", line 706, in draw
bbox, info, descent = textobj._get_layout(renderer)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/text.py", line 309, in _get_layout
ismath=ismath)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 237, in get_text_width_height_descent
self.mathtext_parser.parse(s, self.dpi, prop)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/mathtext.py", line 3293, in parse
box = self._parser.parse(s, font_output, fontsize, dpi)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/mathtext.py", line 2521, in parse
six.text_type(err)]))
ValueError:
^ Double subscript (at char 0), (line:1, col:1)
As the other answer suggests, the problem is trying to use double subscripts in the axis labels. The solution depends on how you would like the labels to look.
If you would like the 1 and the t to both be subscripts then you can use:
$x_{1t}$
If you want the first underscore to be an actual underscore then you can use
$x\_1_t$
The problem is in your labels, you are using a double subscripts:
$x_1_t$
If you change to just using single subscripts it should work (e.g):
$x_1t$

Cartopy plotting issue for interval data

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:

Categories

Resources