18
votes

Is it possible to put tick labels inside the plotting area? I have already tried:

ax.tick_params(axis="y",pad=-.5, left="off",labelleft="on")

and

ax.tick_params(axis="y",direction="in", left="off",labelleft="on")

The former just moves the axis inward, and the latter only moves the ticks not the tick labels.

2

2 Answers

34
votes

I guess you are completely on the right track. The problem is just to find the good parameters for the padding in order to have the ticklabels inside the axes. The padding is measured in points, so it makes sense to use much larger numbers than 0.5. Also the padding is different for x and y axis due to the text's alignment.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.tick_params(axis="y",direction="in", pad=-22)
ax.tick_params(axis="x",direction="in", pad=-15)

plt.show()

enter image description here

4
votes

Update

I completely forgot about the pad param in tick_params. @ImportanceOfBeingErnest’s answer makes use of this and is more appropriate for the question asked.

Nevertheless, I will leave my answer here as an example of how one could achieve the same goal if it weren’t available through a general method like thick_params.


I am not aware of the official way to achieve this. But you can hard code it.

If you want to have the ticks only on the inside, you only need to run:

ax.tick_params(direction="in")

Now, to move the labels inside the plot area, you need to add padding to the ticks, as follows:

TICK_PADDING = -10

xticks = [*ax.xaxis.get_major_ticks(), *ax.xaxis.get_minor_ticks()]
yticks = [*ax.yaxis.get_major_ticks(), *ax.yaxis.get_minor_ticks()]

for tick in (*xticks, *yticks):
        tick.set_pad(TICK_PADDING)

You might have to use different padding for the x and y ticks. In which case you should:

X_TICK_PADDING = -10
Y_TICK_PADDING = -20

xticks = [*ax.xaxis.get_major_ticks(), *ax.xaxis.get_minor_ticks()]
yticks = [*ax.yaxis.get_major_ticks(), *ax.yaxis.get_minor_ticks()]

for tick in xticks:
    tick.set_pad(X_TICK_PADDING)

for tick in yticks:
    tick.set_pad(Y_TICK_PADDING)

It's not pretty but it works. Let me know if this is what you wanted.