matplotlib中用一个文本注释几个点
·
问题:matplotlib中用一个文本注释几个点
我想使用单个注释文本用多个箭头注释多个数据点。我做了一个简单的解决方法:
ax = plt.gca()
ax.plot([1,2,3,4],[1,4,2,6])
an1 = ax.annotate('Test',
xy=(2,4), xycoords='data',
xytext=(30,-80), textcoords='offset points',
arrowprops=dict(arrowstyle="-|>",
connectionstyle="arc3,rad=0.2",
fc="w"))
an2 = ax.annotate('Test',
xy=(3,2), xycoords='data',
xytext=(0,0), textcoords=an1,
arrowprops=dict(arrowstyle="-|>",
connectionstyle="arc3,rad=0.2",
fc="w"))
plt.show()
产生以下结果:
但我真的不喜欢这个解决方案,因为它是......好吧,一个丑陋的肮脏黑客。
除此之外,它还会影响注释的外观(主要是在使用半透明 bbox 等时)。
所以,如果有人得到了一个实际的解决方案,或者至少知道如何实现它,请分享。
解答
我想正确的解决方案将需要太多的努力 - 继承 _AnnotateBase 并自己添加对多个箭头的支持。但是我设法通过添加alpha=0.0来消除影响视觉外观的第二个注释的问题。因此,如果没有人会提供更好的解决方案,这里的更新解决方案:
def my_annotate(ax, s, xy_arr=[], *args, **kwargs):
ans = []
an = ax.annotate(s, xy_arr[0], *args, **kwargs)
ans.append(an)
d = {}
try:
d['xycoords'] = kwargs['xycoords']
except KeyError:
pass
try:
d['arrowprops'] = kwargs['arrowprops']
except KeyError:
pass
for xy in xy_arr[1:]:
an = ax.annotate(s, xy, alpha=0.0, xytext=(0,0), textcoords=an, **d)
ans.append(an)
return ans
ax = plt.gca()
ax.plot([1,2,3,4],[1,4,2,6])
my_annotate(ax,
'Test',
xy_arr=[(2,4), (3,2), (4,6)], xycoords='data',
xytext=(30, -80), textcoords='offset points',
bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3),
arrowprops=dict(arrowstyle="-|>",
connectionstyle="arc3,rad=0.2",
fc="w"))
plt.show()
结果图片:
更多推荐

所有评论(0)