Created
October 6, 2012 18:15
-
-
Save joferkington/3845684 to your computer and use it in GitHub Desktop.
Arrows on the ends of spines for matplotlib
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import matplotlib.pyplot as plt | |
def arrowed_spines(ax=None, arrow_length=20, labels=('', ''), arrowprops=None): | |
xlabel, ylabel = labels | |
if ax is None: | |
ax = plt.gca() | |
if arrowprops is None: | |
arrowprops = dict(arrowstyle='<|-', facecolor='black') | |
for i, spine in enumerate(['left', 'bottom']): | |
# Set up the annotation parameters | |
t = ax.spines[spine].get_transform() | |
xy, xycoords = [1, 0], ('axes fraction', t) | |
xytext, textcoords = [arrow_length, 0], ('offset points', t) | |
ha, va = 'left', 'bottom' | |
# If axis is reversed, draw the arrow the other way | |
top, bottom = ax.spines[spine].axis.get_view_interval() | |
if top < bottom: | |
xy[0] = 0 | |
xytext[0] *= -1 | |
ha, va = 'right', 'top' | |
if spine is 'bottom': | |
xarrow = ax.annotate(xlabel, xy, xycoords=xycoords, xytext=xytext, | |
textcoords=textcoords, ha=ha, va='center', | |
arrowprops=arrowprops) | |
else: | |
yarrow = ax.annotate(ylabel, xy[::-1], xycoords=xycoords[::-1], | |
xytext=xytext[::-1], textcoords=textcoords[::-1], | |
ha='center', va=va, arrowprops=arrowprops) | |
return xarrow, yarrow |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice piece of code! A usage example would be nice, and maybe a comment on copyright / license