MnZ*_*ZrK 7 python annotate 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()
Run Code Online (Sandbox Code Playgroud)
产生以下结果:
但我真的不喜欢这个解决方案,因为它是......好吧,一个丑陋的黑客.
除此之外,它还会影响注释的外观(主要是使用半透明的bbox等).
所以,如果有人得到了实际的解决方案或者至少知道如何实现它,请分享.
MnZ*_*ZrK 14
我想正确的解决方案需要花费太多精力 - 继承_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()
Run Code Online (Sandbox Code Playgroud)
结果图:
归档时间: |
|
查看次数: |
4461 次 |
最近记录: |