To create 5 subplots I used:
`ax = plt.subplots(5, sharex=True)`
Then, I want to remove the first and the last label tick of each y-axis subplot (because they overplot each other), I used:
`plt.setp([a.get_yticklabels()[0::-1] for a in ax[0:5]], visible=False)`
But this just removes some of the ticks, I don't understand the logic behind.
To remove the ticks on the y-axis, tick_params() method has an attribute named left and we can set its value to False and pass it as a parameter inside the tick_params() function. It removes the tick on the y-axis.
To hide any of the axes in your graph layer, open the Axis dialog box and then clear the Show Axis & Ticks check box on the Title & Format tab when the desired axis is selected from the Selection list box.
We can turn off the axes of subplots in Matplotlib using axis() and set_axis_off() methods for axes objects. We can also turn off axes using the axis() method for the pyplot object. To turn off axis for X-axis in particular we use axes. get_xaxis().
By default, in the Matplotlib library, plots are plotted on a white background. Therefore, setting the color of tick labels as white can make the axis tick labels hidden.
You should be careful with the result of the first call. You might wanna call it like
fig, ax = plt.subplots(5, sharex=True, squeeze=True)
If you do this, you can then just iterate through all the axes:
for a in ax:
# get all the labels of this axis
labels = a.get_yticklabels()
# remove the first and the last labels
labels[0] = labels[-1] = ""
# set these new labels
a.set_yticklabels(labels)
If you want to keep your style of hiding the labels, you could use
for a in ax:
plt.setp(a.get_yticklabels()[0], visible=False)
plt.setp(a.get_yticklabels()[-1], visible=False)
Note: You may have to call draw()
before accessing the tick labels (see: https://stackoverflow.com/a/41131528/8144672). For example, when plotting to a PDF, you have to call plt.gcf().canvas.draw()
before get_xticklabels()
.
Use MaxNLocator:
from matplotlib.ticker import MaxNLocator
ax.yaxis.set_major_locator(MaxNLocator(prune='both'))
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