Remove first and last ticks label of each y-axis subplot

matplotlib, python

Solution

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()`.

Problem

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.

Original source

Related problems