20

Is there a way in matplotlib to set ticks between the labels and the axis as it is by default in Origin? The examples section online does not show a single plot with this feature. I like having ticks outside the plotting area because sometimes the plot hides the ticks when inside.

user1850133
  • 2,833
  • 9
  • 29
  • 39

2 Answers2

34

To set the just the major ticks:

ax = plt.gca()
ax.get_yaxis().set_tick_params(direction='out')
ax.get_xaxis().set_tick_params(direction='out')
plt.draw()

to set all ticks (minor and major),

ax.get_yaxis().set_tick_params(which='both', direction='out')
ax.get_xaxis().set_tick_params(which='both', direction='out')
plt.draw()

to set both the x and y axis at the same time:

ax = plt.gca()
ax.tick_params(direction='out')

axis level doc and axes level doc

To shift the tick labels relative to the ticks use pad. Compare

ax.tick_params(direction='out', pad=5)
plt.draw()

with

ax.tick_params(direction='out', pad=15)
plt.draw()
tacaswell
  • 84,579
  • 22
  • 210
  • 199
  • the last one seems to work fine. Now I have to find a way to move the tick labels by the same distance. In fact I mistakenly put twice the code line 'ax.tick_params(which='both', direction='out', length=25, width=6)' and surprisingly it reduced the size of the plot by the needed amount to have a perfect plot. But I don't know why. – user1850133 Feb 05 '13 at 17:39
  • Did you remember to include a `plt.draw()`? You can adjust the space between the label and the tick with the `pad` kwarg. – tacaswell Feb 05 '13 at 17:49
  • here http://matplotlib.org/api/pyplot_api.html?highlight=pyplot.draw#matplotlib.pyplot.draw ; they say that plt.draw() is not needed is the sequence of modification ends with show(); though I tried it before checking the definition of plt.draw(): it didn't not change anything. what is `pad`? – user1850133 Feb 06 '13 at 08:38
  • @user1850133 See the documentation on `tick_param` (http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.tick_params) It sets the space between the tick and the label. – tacaswell Feb 06 '13 at 14:34
  • no option allows positioning of the tick labels with tick_params – user1850133 Feb 10 '13 at 18:00
  • @user1850133 If this solved your problem can you please accept it? – tacaswell Aug 18 '13 at 19:29
  • Oddly enough, I am having the same issue, that I cannot move the ticks to the outside. It seems like the command is simply ignored. However, this seems to be related to the axis artist I am using. – Schorsch Aug 08 '14 at 19:30
  • To set a specific axis; ax.tick_params(direction='out', axis='x', pad=5) – nvd Nov 19 '14 at 17:54
0

I guess you need this:

By getting the subplot object you can play with your ticks

ax = plt.subplot(111)
yax = ax.get_yaxis()
plt.xticks(y_pos, city)
xtickNames=ax.set_xticklabels(city)
plt.setp(xtickNames, rotation=45, fontsize=10)

Following is the output with 45 degrees rotated ticks

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93