plt.savefig(): 值错误:dash列表中的所有值必须为正数
运行下面链接中的代码时出现了错误。至于和图像有关的部分,我不知道什么是“dash list”。
matplotlib.pyplot as plt
...
plt.savefig('tutorial10.png',dpi=300)
返回错误的部分:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-21-edce1701d7a3> in <module>()
60 ax.add_collection(lines)
61
--> 62 plt.savefig('tutorial10.png',dpi=300)
63
64 plt.show()
...
C:\Anaconda\lib\site-packages\matplotlib\backend_bases.pyc in set_dashes(self, dash_offset, dash_list)
902 dl = np.asarray(dash_list)
903 if np.any(dl <= 0.0):
--> 904 raise ValueError("All values in the dash list must be positive")
905 self._dashes = dash_offset, dash_list
906
http://www.geophysique.be/2013/02/12/matplotlib-basemap-tutorial-10-shapefiles-unleached-continued/
3 个回答
0
我想我解决了这个问题。
我的Matplotlib版本是3.7.2,不过在3.6.0版本时也遇到过同样的问题。以下是我做的步骤:
1. 找到这个路径:C:\Users\USER_NAME\AppData\Local\Programs\Python\Python311\Lib\site-packages\matplotlib
2. 打开文件:lines.py进行编辑
3. 找到名为_scale_dashes的函数:
def _scale_dashes(offset, dashes, lw):
if not mpl.rcParams['lines.scale_dashes']:
return offset, dashes
scaled_offset = offset * lw
scaled_dashes = ([x * lw if x is not None else None for x in dashes]
if dashes is not None else None)
return scaled_offset, scaled_dashes
然后我把第一个if语句修改成了这样:
def _scale_dashes(offset, dashes, lw):
if not mpl.rcParams['lines.scale_dashes'] or lw == 0:
return offset, dashes
scaled_offset = offset * lw
scaled_dashes = ([x * lw if x is not None else None for x in dashes]
if dashes is not None else None)
return scaled_offset, scaled_dashes
实际上,问题出在_scale_dashes函数的输出上,当lw等于0时。在某些情况下,输出会变成:(0, [0, 0]),这就会导致错误。
raise ValueError(
ValueError: At least one value in the dash list must be positive
因为这个元组的第二个元素是一个包含0值的列表,而这些0值是因为在_scale_dashes函数中用lw(也就是0)去乘的结果。
1
在matplotlib 3.6.2这个版本中,当你用零的线宽来画虚线时,也可能会出现这个错误,比如你写了plt.plot(1, 1, ls='--', lw=0)
。
4
在你提供的代码中,有以下几行:
m.drawparallels(np.arange(y1,y2,2.),labels=[1,0,0,0],color='black',dashes=[1,0],labelstyle='+/-',linewidth=0.2) # draw parallels
m.drawmeridians(np.arange(x1,x2,2.),labels=[0,0,0,1],color='black',dashes=[1,0],labelstyle='+/-',linewidth=0.2)
在这些行中,参数 dashes
被设置为 [1,0]
。根据你的错误信息,数组 dashes
中的所有值必须是严格大于零的。这就是你收到异常的原因(因为你的数组 dashes
中包含了零)。