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

2024-10-02 10:31:38 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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()

产生以下结果: enter image description here

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

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

所以,如果有人得到了一个实际的解决方案,或者至少有一个如何实现它的想法,请分享。在


Tags: testdatapltaxdictxyannotatexycoords
2条回答

我想正确的解决方案将需要太多的努力-子类化_annotationbase并添加对多个箭头的支持。但是我通过添加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()

结果图片: enter image description here

就个人而言,我会使用set axes fraction coordinates来保证文本标签的位置,然后通过使用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()

View Example Plot

相关问题 更多 >

    热门问题