“plt.savefig”现在会引发 TypeError

如何解决“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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-