public
Created

Arrows on the ends of spines for matplotlib

  • Download Gist
arrowed_spines.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.