I would like to make a matplotlib plot having only the left and bottom axes, and also the ticks facing outwards and not inwards as the default. I found two questions that address both topics separately:
In matplotlib, how do you draw R-style axis ticks that point outward from the axes?
How can I remove the top and right axis in matplotlib?
Each of them work on its own, but unfortunately, both solutions seem to be incompatible with each other. After banging my head for some time, I found a warning in the axes_grid
documentation that says
"some commands (mostly tick-related) do not work"
This is the code that I have:
from matplotlib.pyplot import *
from mpl_toolkits.axes_grid.axislines import Subplot
import matplotlib.lines as mpllines
import numpy as np
#set figure and axis
fig = figure(figsize=(6, 4))
#comment the next 2 lines to not hide top and right axis
ax = Subplot(fig, 111)
fig.add_subplot(ax)
#uncomment next 2 lines to deal with ticks
#ax = fig.add_subplot(111)
#calculate data
x = np.arange(0.8,2.501,0.001)
y = 4*((1/x)**12 - (1/x)**6)
#plot
ax.plot(x,y)
#do not display top and right axes
#comment to deal with ticks
ax.axis["right"].set_visible(False)
ax.axis["top"].set_visible(False)
#put ticks facing outwards
#does not work when Sublot is called!
for l in ax.get_xticklines():
l.set_marker(mpllines.TICKDOWN)
for l in ax.get_yticklines():
l.set_marker(mpllines.TICKLEFT)
#done
show()
Changing your code slightly, and using a trick (or a hack?) from this link, this seems to work:
import numpy as np
import matplotlib.pyplot as plt
#comment the next 2 lines to not hide top and right axis
fig = plt.figure()
ax = fig.add_subplot(111)
#uncomment next 2 lines to deal with ticks
#ax = fig.add_subplot(111)
#calculate data
x = np.arange(0.8,2.501,0.001)
y = 4*((1/x)**12 - (1/x)**6)
#plot
ax.plot(x,y)
#do not display top and right axes
#comment to deal with ticks
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
## the original answer:
## see http://old.nabble.com/Ticks-direction-td30107742.html
#for tick in ax.xaxis.majorTicks:
# tick._apply_params(tickdir="out")
# the OP way (better):
ax.tick_params(axis='both', direction='out')
ax.get_xaxis().tick_bottom() # remove unneeded ticks
ax.get_yaxis().tick_left()
plt.show()
If you want outward ticks on all your plots, it might be easier to set the tick direction in the rc file -- on that page search for xtick.direction
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With