I am trying to set an arrow at the end of a an axis in matplotlib. I don\'t want to remove the spines and replace them with pure arrows because I need their functionalities
There is an example showing how to get arrows as axis decorators in the matplotlib documentation using the mpl_toolkits.axisartist toolkit:
from mpl_toolkits.axisartist.axislines import SubplotZero
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = SubplotZero(fig, 111)
fig.add_subplot(ax)
for direction in ["xzero", "yzero"]:
# adds arrows at the ends of each axis
ax.axis[direction].set_axisline_style("-|>")
# adds X and Y-axis from the origin
ax.axis[direction].set_visible(True)
for direction in ["left", "right", "bottom", "top"]:
# hides borders
ax.axis[direction].set_visible(False)
x = np.linspace(-0.5, 1., 100)
ax.plot(x, np.sin(x*np.pi))
plt.show()
For many cases, the use of the mpl_toolkits.axisartist.axislines module is not desired. In that case one can also easily get arrow heads by using triangles as markers on the top of the spines:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 100)
y = 2 * np.sin(x)
rc = {"xtick.direction" : "inout", "ytick.direction" : "inout",
"xtick.major.size" : 5, "ytick.major.size" : 5,}
with plt.rc_context(rc):
fig, ax = plt.subplots()
ax.plot(x, y)
ax.spines['left'].set_position('zero')
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# make arrows
ax.plot((1), (0), ls="", marker=">", ms=10, color="k",
transform=ax.get_yaxis_transform(), clip_on=False)
ax.plot((0), (1), ls="", marker="^", ms=10, color="k",
transform=ax.get_xaxis_transform(), clip_on=False)
plt.show()