2013-08-22 55 views
5

如何注释我的一系列数据?例如,假设从x = 5x = 10的数据大于某个截止点,我怎么能在图上表明这一点。如果我是手工注释,我会在范围上方画一个大支架,并在支架上面写上我的注释。在matplotlib中注释数据范围

我看到的最接近的方法是使用arrowstyle='<->'connectionstyle='bar',使两个箭头指向数据边缘并用连线连接它们的尾部。但这并不是正确的做法;您为注释输入的文本将在箭头之下结束,而不是在条形上方。

这里是我的尝试,它的结果一起:

annotate(' ', xy=(1,.5), xycoords='data', 
      xytext=(190, .5), textcoords='data', 
      arrowprops=dict(arrowstyle="<->", 
          connectionstyle="bar", 
          ec="k", 
          shrinkA=5, shrinkB=5, 
          ) 
      ) 

Annotation attempt

我试图解决的另一个问题是,标注支架的田字并没有真正说清楚,我突出显示范围(不同于例如大括号)。但是,我认为在这一点上这只是个挑剔。

+0

使用两种注解,一个有文字,但没有箭头,一个带箭头,但没有文本。另请参阅'axvspan' http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.axvspan – tacaswell

+0

也最好显示您尝试过的内容(使用代码段)。 – tacaswell

+0

@tcaswell我想过使用两个注释,但是这涉及手动定位文本,并且如果范围移动,必须手动更新两个注释。看起来这是一个普遍存在的问题,即存在更优化的解决方案。 – ari

回答

4

你可以只是包装了这一切的功能:

def add_range_annotation(ax, start, end, txt_str, y_height=.5, txt_kwargs=None, arrow_kwargs=None): 
    """ 
    Adds horizontal arrow annotation with text in the middle 

    Parameters 
    ---------- 
    ax : matplotlib.Axes 
     The axes to draw to 

    start : float 
     start of line 

    end : float 
     end of line 

    txt_str : string 
     The text to add 

    y_height : float 
     The height of the line 

    txt_kwargs : dict or None 
     Extra kwargs to pass to the text 

    arrow_kwargs : dict or None 
     Extra kwargs to pass to the annotate 

    Returns 
    ------- 
    tuple 
     (annotation, text) 
    """ 

    if txt_kwargs is None: 
     txt_kwargs = {} 
    if arrow_kwargs is None: 
     # default to your arrowprops 
     arrow_kwargs = {'arrowprops':dict(arrowstyle="<->", 
          connectionstyle="bar", 
          ec="k", 
          shrinkA=5, shrinkB=5, 
          )} 

    trans = ax.get_xaxis_transform() 

    ann = ax.annotate('', xy=(start, y_height), 
         xytext=(end, y_height), 
         transform=trans, 
         **arrow_kwargs) 
    txt = ax.text((start + end)/2, 
        y_height + .05, 
        txt_str, 
        **txt_kwargs) 


    if plt.isinteractive(): 
     plt.draw() 
    return ann, txt 

或者,

start, end = .6, .8 
ax.axvspan(start, end, alpha=.2, color='r') 
trans = ax.get_xaxis_transform() 
ax.text((start + end)/2, .5, 'test', transform=trans) 
+0

获得自己的方法不是一种常见的操作? – ari

+0

我不知道现有的,但我只写了一个;)如果你可以提供一些反馈使用的东西,我会建议添加到图书馆作为内置。 – tacaswell

+0

他们都是很好的选择,感谢您分享它们。您提供的功能已经足够满足大多数情况,但如果您正在寻找改进方法,我可以考虑一些建议。 – ari