如何解决“plt.savefig”现在会引发 TypeError
我有一个曾经运行得很好的代码。但是,它现在引发了错误
TypeError: object of type 'NoneType' has no len()
在行 plt.savefig
中。我使用 Jupyter 笔记本(通过 Anaconda)。
更新:问题出在“ax.legend”上。当它被注释时,代码就会运行。
我查看了 here,但找不到解决方案。
代码:
import matplotlib.pyplot as plt
.
.
.
plt.rc('xtick',labelsize=18)
plt.rc('ytick',labelsize=18)
fig,ax = plt.subplots(figsize=(15,15))
for label,color,shape,inds in zip(labels,colors,shapes,indss):
ax.scatter(pca_coor[inds,0],pca_coor[inds,1],c=color,label=label,s=150,marker=shape)
ax.legend(labels,prop={'size': 20})
ax.set_title('title',fontdict={'fontsize': 30,'fontweight': 'medium'})
ax.set_xlabel('PC 1',fontdict={'fontsize': 22,'fontweight': 'medium'})
ax.set_ylabel('PC 2','fontweight': 'medium'})
# save the figure to file
plt.savefig('picfile.png')
plt.close()
这是整个错误:
-> 2486 plt.savefig('picfile.png')
2487 #plt.clf()
2488 plt.close()
~\Anaconda3\lib\site-packages\matplotlib\pyplot.py in savefig(*args,**kwargs)
935 def savefig(*args,**kwargs):
936 fig = gcf()
--> 937 res = fig.savefig(*args,**kwargs)
938 fig.canvas.draw_idle() # need this if 'transparent=True' to reset colors
939 return res
~\Anaconda3\lib\site-packages\matplotlib\figure.py in savefig(self,fname,transparent,**kwargs)
2957 patch.set_edgecolor('none')
2958
-> 2959 self.canvas.print_figure(fname,**kwargs)
2960
2961 if transparent:
~\Anaconda3\lib\site-packages\matplotlib\backend_bases.py in print_figure(self,filename,dpi,facecolor,edgecolor,orientation,format,bbox_inches,pad_inches,bbox_extra_artists,backend,**kwargs)
2259 orientation=orientation,2260 bbox_inches_restore=_bbox_inches_restore,-> 2261 **kwargs)
2262 finally:
2263 if bbox_inches and restore_bbox:
~\Anaconda3\lib\site-packages\matplotlib\backend_bases.py in wrapper(*args,**kwargs)
1667 kwargs.pop(arg)
1668
-> 1669 return func(*args,**kwargs)
1670
1671 return wrapper
~\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in print_png(self,filename_or_obj,metadata,pil_kwargs,*args)
506 *metadata*,including the default 'Software' key.
507 """
--> 508 FigureCanvasAgg.draw(self)
509 mpl.image.imsave(
510 filename_or_obj,self.buffer_rgba(),format="png",origin="upper",~\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in draw(self)
404 (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar
405 else nullcontext()):
--> 406 self.figure.draw(self.renderer)
407 # A GUI class may be need to update a window using this draw,so
408 # don't forget to call the superclass.
~\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist,renderer,*args,**kwargs)
72 @wraps(draw)
73 def draw_wrapper(artist,**kwargs):
---> 74 result = draw(artist,**kwargs)
75 if renderer._rasterizing:
76 renderer.stop_rasterizing()
~\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist,**kwargs)
49 renderer.start_filter()
50
---> 51 return draw(artist,**kwargs)
52 finally:
53 if artist.get_agg_filter() is not None:
~\Anaconda3\lib\site-packages\matplotlib\figure.py in draw(self,renderer)
2733 self.patch.draw(renderer)
2734 mimage._draw_list_compositing_images(
-> 2735 renderer,self,artists,self.suppressComposite)
2736
2737 for sfig in self.subfigs:
~\Anaconda3\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer,parent,suppress_composite)
130 if not_composite or not has_images:
131 for a in artists:
--> 132 a.draw(renderer)
133 else:
134 # Composite any adjacent images together
~\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist,**kwargs)
52 finally:
53 if artist.get_agg_filter() is not None:
~\Anaconda3\lib\site-packages\matplotlib\_api\deprecation.py in wrapper(*inner_args,**inner_kwargs)
429 else deprecation_addendum,430 **kwargs)
--> 431 return func(*inner_args,**inner_kwargs)
432
433 return wrapper
~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in draw(self,inframe)
2923 renderer.stop_rasterizing()
2924
-> 2925 mimage._draw_list_compositing_images(renderer,artists)
2926
2927 renderer.close_group('axes')
~\Anaconda3\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer,**kwargs)
52 finally:
53 if artist.get_agg_filter() is not None:
~\Anaconda3\lib\site-packages\matplotlib\legend.py in draw(self,renderer)
612
613 self.legendPatch.draw(renderer)
--> 614 self._legend_box.draw(renderer)
615
616 renderer.close_group('legend')
~\Anaconda3\lib\site-packages\matplotlib\offsetbox.py in draw(self,renderer)
366 for c,(ox,oy) in zip(self.get_visible_children(),offsets):
367 c.set_offset((px + ox,py + oy))
--> 368 c.draw(renderer)
369
370 bbox_artist(self,fill=False,props=dict(pad=0.))
~\Anaconda3\lib\site-packages\matplotlib\offsetbox.py in draw(self,renderer)
692 if self._clip_children and not (c.clipbox or c._clippath):
693 c.set_clip_path(tpath)
--> 694 c.draw(renderer)
695
696 bbox_artist(self,props=dict(pad=0.))
~\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist,**kwargs)
52 finally:
53 if artist.get_agg_filter() is not None:
~\Anaconda3\lib\site-packages\matplotlib\collections.py in draw(self,renderer)
1007 def draw(self,renderer):
1008 self.set_sizes(self._sizes,self.figure.dpi)
-> 1009 super().draw(renderer)
1010
1011
~\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist,renderer)
378 do_single_path_optimization = False
379 if (len(paths) == 1 and len(trans) <= 1 and
--> 380 len(facecolors) == 1 and len(edgecolors) == 1 and
381 len(self._linewidths) == 1 and
382 all(ls[1] is None for ls in self._linestyles) and
TypeError: object of type 'NoneType' has no len()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\Anaconda3\lib\site-packages\IPython\core\formatters.py in __call__(self,obj)
339 pass
340 else:
--> 341 return printer(obj)
342 # Finally look for special method names
343 method = get_real_method(obj,self.print_method)
~\Anaconda3\lib\site-packages\IPython\core\pylabtools.py in <lambda>(fig)
246
247 if 'png' in formats:
--> 248 png_formatter.for_type(Figure,lambda fig: print_figure(fig,'png',**kwargs))
249 if 'retina' in formats or 'png2x' in formats:
250 png_formatter.for_type(Figure,lambda fig: retina_figure(fig,**kwargs))
~\Anaconda3\lib\site-packages\IPython\core\pylabtools.py in print_figure(fig,fmt,**kwargs)
130 FigureCanvasBase(fig)
131
--> 132 fig.canvas.print_figure(bytes_io,**kw)
133 data = bytes_io.getvalue()
134 if fmt == 'svg':
~\Anaconda3\lib\site-packages\matplotlib\backend_bases.py in print_figure(self,**kwargs)
2228 else suppress())
2229 with ctx:
-> 2230 self.figure.draw(renderer)
2231
2232 if bbox_inches:
~\Anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist,renderer)
378 do_single_path_optimization = False
379 if (len(paths) == 1 and len(trans) <= 1 and
--> 380 len(facecolors) == 1 and len(edgecolors) == 1 and
381 len(self._linewidths) == 1 and
382 all(ls[1] is None for ls in self._linestyles) and
TypeError: object of type 'NoneType' has no len()
<Figure size 1080x1080 with 1 Axes>
matplotlib 版本:3.4.0
提前致谢。
解决方法
我通过将 ax.scatter 中的“c”更改为“color”,并从 ax.legend 中删除了“标签”,设法解决了这个问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。