matplotlib annotate xycoords=('data','axes fraction') => TypeError: 'NoneType' 不是可迭代对象
>>> import matplotlib
>>> matplotlib.__version__
'0.99.1.1'
下面的代码可以正常运行:
import matplotlib.pyplot as plt
plt.figure()
ax=plt.axes([.1, .1, .8, .8])
ax.annotate('++++', xy=(.5,.2), xycoords='data')
ax.annotate('aaaa', xy=(.5,.4), xycoords='axes fraction')
#ax.annotate('bbbb', xy=(.5,.6), xycoords=('data', 'axes fraction'))
plt.show()
但是注释掉的 ax.annotate 会报错:
TypeError: 'NoneType' object is not iterable
根据当前的文档,这段代码应该是正确的:
From: http://matplotlib.sourceforge.net/users/annotations_guide.html
4. A tuple of two coordinate specification.
The first item is for x-coordinate and
the second is for y-coordinate.
For example,
annotate("Test", xy=(0.5, 1), xycoords=("data", "axes fraction"))
0.5 is in data coordinate, and 1 is in normalized axes coordinate.
有没有人知道这是怎么回事?
编辑:
自从第一次发帖以来,我一直在寻找解决办法,并发现了另一个问题。当 xycoords='data' 时,如果注释的内容超出了坐标轴的范围,即使 clip_on=False,注释仍然会被裁剪掉。这里有段代码可以演示这个问题:
import matplotlib.pyplot as plt
plt.figure()
ax=plt.axes([.1, .1, .8, .8])
ax.annotate('cccc', xy=(.3, .5), xycoords='data', clip_on=False)
ax.annotate('dddd', xy=(.3,-.1), xycoords='data', clip_on=False)
ax.annotate('eeee', xy=(.6,-.1), xycoords='axes fraction', clip_on=False)
plt.show()
1 个回答
5
在matplotlib的版本1.0
中,增加了使用元组来表示不同的x和y变换的方法,用于annotate
。如果你感兴趣,可以查看这个相关的提交记录。要使用这个功能,你需要升级到最新版本。
对于第二个问题,这其实是文档中说明的行为。(clip_on
是一个通用的matplotlib文本艺术家参数。显然,注释艺术家的表现方式不一样。)
来源: http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.annotate
annotation_clip属性控制注释在超出坐标轴区域时的可见性。如果设置为True,只有当xy在坐标轴内时,注释才会被绘制。如果设置为False,注释无论位置如何都会被绘制。默认值是None,只有当xycoords为“data”时,才表现得像True。
你需要使用annotation_clip
参数,来替代之前的设置:
import matplotlib.pyplot as plt
plt.figure()
ax=plt.axes([.1, .1, .8, .8])
ax.annotate('cccc', xy=(.3, .5), xycoords='data', annotation_clip=False)
ax.annotate('dddd', xy=(.3,-.1), xycoords='data', annotation_clip=False)
ax.annotate('eeee', xy=(.6,-.1), xycoords='axes fraction', annotation_clip=False)
plt.show()
更多讨论可以查看这个matplotlib用户讨论串(另外要注意,annotation_clip
参数在0.99.1
版本中可能有问题,所以你可能需要使用那里的解决方法。)