4

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:

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()
Community
  • 1
  • 1
englebip
  • 955
  • 1
  • 11
  • 17

1 Answers1

8

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

ev-br
  • 24,968
  • 9
  • 65
  • 78
  • 1
    Indeed, this works perfectly. Actually, I just discovered that the last `for` loop can be avoided by using `ax.tick_params(axis='both', direction='out')`, which also sets the outward ticks on the y-axis at the same time. Another thing that needs to be done is to remove the ticks on the top and right axis, with `ax.get_xaxis().tick_bottom()` and `ax.get_yaxis().tick_left()` respectively. And thanks for the `rc` tip, that will be useful! – englebip Feb 03 '12 at 12:23