matplotlib annotate xycoords =('data','axes fraction')=> TypeError:'NoneType'对象不可迭代

5 python matplotlib

>>> import matplotlib
>>> matplotlib.__version__
'0.99.1.1'
Run Code Online (Sandbox Code Playgroud)

运行以下代码:

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()
Run Code Online (Sandbox Code Playgroud)

但注释掉的ax.annotate给出了一个错误:

TypeError: 'NoneType' object is not iterable
Run Code Online (Sandbox Code Playgroud)

根据当前的文档,它应该是正确的代码:

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.
Run Code Online (Sandbox Code Playgroud)

关于发生了什么的任何想法?

编辑:自首次发布以来,我一直在寻找解决方法,并发现了另一个问题.当xycoords ='data'时,即使使用clip_on = False,如果annotataion落在轴之外,它仍会被剪裁.以下代码演示了这一点:

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()
Run Code Online (Sandbox Code Playgroud)

Joe*_*ton 5

annotate在 matplotlib 中添加了使用元组来指示不同的 x 和 y 变换1.0。 如果有人感兴趣,这是相关的提交。您需要升级到最新版本才能使用它。

对于第二个问题,这实际上是记录在案的行为。(clip_on是一个通用的 matplotlib 文本艺术家 kwarg。显然,注释艺术家的行为方式不同。)

来自:http : //matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.annotate

annotation_clip 属性控制注释超出轴区域时的可见性。如果为 True,则仅当 xy 位于坐标区内时才会绘制注释。如果为 False,则无论其位置如何,都将始终绘制注释。默认为无,仅当 xycoords 为“数据”时才表现为 True。

你需要使用annotation_clipkwarg,而不是:

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()
Run Code Online (Sandbox Code Playgroud)

有关更多讨论,请参阅matplotlib-users 列表上的此线程(还要注意annotation_clipkwarg 可能已损坏0.99.1,因此您可能需要在那里使用解决方法。)