Python 在matplotlib中用一个文本注释多个点

Python 在matplotlib中用一个文本注释多个点,python,matplotlib,annotate,Python,Matplotlib,Annotate,我想使用单个注释文本用几个箭头注释几个数据点。我做了一个简单的变通方法: 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="-|>", connection

我想使用单个注释文本用几个箭头注释几个数据点。我做了一个简单的变通方法:

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()
产生以下结果:

但我不太喜欢这个解决方案,因为它是。。。一个丑陋肮脏的黑客

除此之外,它还影响注释的外观(主要是在使用半透明bboxes等时)


因此,如果有人得到了一个实际的解决方案或至少是一个如何实现它的想法,请与我们分享。

我想正确的解决方案需要付出太多的努力-子类化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()
结果图片:

就个人而言,我会使用设置轴分数坐标来保证文本标签的位置,然后通过使用color关键字参数使除一个标签外的所有标签都可见

ax = plt.gca()
ax.plot([1,2,3,4],[1,4,2,6])
label_frac_x = 0.35
label_frac_y = 0.2

#label first point
ax.annotate('Test', 
  xy=(2,4), xycoords='data', color='white',
  xytext=(label_frac_x,label_frac_y), textcoords='axes fraction',
  arrowprops=dict(arrowstyle="-|>",
                  connectionstyle="arc3,rad=0.2",
                  fc="w"))

#label second point    
ax.annotate('Test', 
      xy=(3,2), xycoords='data', color='black',
      xytext=(label_frac_x, label_frac_y), textcoords='axes fraction',
      arrowprops=dict(arrowstyle="-|>",
                      connectionstyle="arc3,rad=0.2",
                      fc="w"))
plt.show()

你应该接受这个答案(你可以回答你自己的问题,没关系)。我知道,但stackoverflow不让我这么做:)我需要等2天左右。