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.
With matplotlib version 3.3. 0, the matplotlib functions set_xlabel and set_ylabel have a new parameter “loc” that can help adjust the positions of axis labels. For the x-axis label, it supports the values 'left', 'center', or 'right' to place the label towards left/center/right.
If you know the tick positions, you can do something like for pos, tick in zip(ticks, ax. xaxis. get_majorticklabels()): tick. set_x(pos - 0.1) tick.
MatPlotLib with Python Plot x and y data points using plot() method. To locate minor ticks, use set_minor_locator() method. To show the minor ticks, use grid(which='minor'). To display the figure, use show() method.
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()
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.
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