你可以只是包裝了這一切的功能:
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)
使用兩種註解,一個有文字,但沒有箭頭,一個帶箭頭,但沒有文本。另請參閱'axvspan' http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.axvspan – tacaswell
也最好顯示您嘗試過的內容(使用代碼段)。 – tacaswell
@tcaswell我想過使用兩個註釋,但是這涉及手動定位文本,並且如果範圍移動,必須手動更新兩個註釋。看起來這是一個普遍存在的問題,即存在更優化的解決方案。 – ari