Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 465
Py-ser Avatar asked Dec 03 '13 11:12

Py-ser


People also ask

How do I get rid of Y ticks?

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.

How do I remove the Y-axis labels in origin?

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.

How do you remove the axes from a subplot?

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

How do I hide tick labels?

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.


2 Answers

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

like image 95
David Zwicker Avatar answered Sep 19 '22 13:09

David Zwicker


Use MaxNLocator:

from matplotlib.ticker import MaxNLocator
ax.yaxis.set_major_locator(MaxNLocator(prune='both'))
like image 22
Ruggero Turra Avatar answered Sep 18 '22 13:09

Ruggero Turra