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

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'))