Skip to content

Instantly share code, notes, and snippets.

@tacaswell
Created August 26, 2013 01:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tacaswell/6337457 to your computer and use it in GitHub Desktop.
Save tacaswell/6337457 to your computer and use it in GitHub Desktop.
gist for working on annotation range function
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
@arijun
Copy link

arijun commented Aug 26, 2013

Here are some suggestions:

  • Allow for arbitrary rotation (easily done with a start and end points getting their own xy coordinates)
  • Other shapes besides square brackets. I tried doing this by changing connectionstyle, but that didn't work. Could be done by using two arrows instead of one connected arrow, but might require too much of a retool.
  • Center the text by default
  • Perhaps a value that allows you to vary the hight of the bracket? I.e., allows you to set the distance between the tip of the arrows and the bar connecting them?

I have other suggestions, but they start to bloat what is probably better off a one trick pony. Let me know if you'd like to hear them too.

@tacaswell
Copy link
Author

@arijun hearing them is good, implementations are better ;)

@tacaswell
Copy link
Author

and I think if you pass in different arrowprops into arrow_kwargs you can do some of what you want.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment