简体   繁体   中英

Matplotlib: Hiding specific y-tick labels not working when ticks on the right side of plot

I'm creating a subplot figure with 2 columns and a number of rows. I'm using the following code to move my tick labels and axis label to the right side for the right column (but still keeping the tick marks on both sides):

fig, ax = plt.subplots(4, 2, sharex=False, sharey=False)
fig.subplots_adjust(wspace=0, hspace=0)
for a in ax[:,1]:
  a.yaxis.tick_right()
  a.yaxis.set_ticks_position('both')
  a.yaxis.set_label_position('right')

Then, because the subplots are close together (which is what I want, I don't want any padding in between the plots), the top and bottom y-tick labels overlap between plots. I have attempted to fix this using the method described here (this selects only those ticks that are inside the view interval - check the link for more info):

import matplotlib.transforms as mtransforms 
def get_major_ticks_within_view_interval(axis):
    interval = axis.get_view_interval()
    ticks_in_view_interval = []
    for tick, loc in zip(axis.get_major_ticks(), axis.get_major_locator()()):
        if mtransforms.interval_contains(interval, loc):
            ticks_in_view_interval.append(tick)
    return ticks_in_view_interval 

for i,a in enumerate(ax.ravel()):
    nplots = len(ax.ravel())
    yticks = get_major_ticks_within_view_interval(a.yaxis)
    if i != 0 and i != 1:
        yticks[-1].label.set_visible(False)
    if i != nplots-2 and i != nplots-1:
        yticks[0].label.set_visible(False)

This seems to work fine for the left column, but in the right column the overlapping ticks are still visible. Does anyone know why this happens, and how to fix it? I just can't seem to figure it out.

I have finally found the solution, so I figured I'd put it here as well in case someone ever has the same problem (or if I forget what I did, haha). I found out when I happened upon the following page: http://matplotlib.org/1.3.1/users/artists.html

What I didn't realize is that the labels on the left and the right of the y-axis can be modified independently of each other. When using yticks[0].label.set_visible(False) , the label refers only to the left side labels, so the right side labels stay unchanged. To fix it, I replaced

yticks[0].label.set_visible(False)

by

yticks[0].label1.set_visible(False)
yticks[0].label2.set_visible(False)

(and the same for yticks[-1] ). Now it works like a charm!

Generally I've found that problems with overlap in matplotlib can be solved by using

plt.tight_layout()

have you tried that?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM