简体   繁体   中英

How to delete axis label for just one tick in matplotlib

I am plotting up several adjacent panels with matplotlib. I have the problem that some of the axis labels overlap where the panels meet. A minimum working example and sample image follow.

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(4,8))
ax1 = fig.add_axes([.25,.5,.5,.25])
ax2 = fig.add_axes([.25,.25,.5,.25])

ax1.set_xticklabels([])

fig.savefig("temp.pdf")

在此处输入图片说明

As you can see in the image, the 0.0 of the top panel and the 1.0 of the bottom panel are in the same place. I am trying to get the 1.0 of the bottom panel to not show up but still have the remaining labels on the axis show up. Nothing I've tried has worked. Things I have tried:

#This just doesn't do anything
from matplotlib.ticker import MaxNLocator
ax3.xaxis.set_major_locator(MaxNLocator(prune='upper'))

#This produces the image shown below
labels = [item for item in ax2.get_yticklabels()]
labels[-1].text = ''
ax2.set_yticklabels(labels) 

#This also produces the image shown below
labels = ax2.get_yticklabels()
labels[-1].set_text('')
ax2.set_yticklabels(labels) 

在此处输入图片说明

The image above is produced by the last two of the three blocks of code immediately before the image. The strange y-axis labels occur whether or not the line labels[-1].text = '' is included.

You will want to grab all the yticklabels of the axes, and then set them using all but the last one. An important point here (especially with newer versions of matplotlib) is that you must display the figure and refresh the canvas before fetching the ytick labels so that their default position is already computed.

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(4,8))
ax1 = fig.add_axes([.25,.5,.5,.25])
ax2 = fig.add_axes([.25,.25,.5,.25])

ax1.set_xticklabels([])

# Important to render initial ytick labels
fig.show()
fig.canvas.draw()

# Remove the last ytick label
labels = [tick.get_text() for tick in ax2.get_yticklabels()]
ax2.set_yticklabels(labels[:-1])

# Refresh the canvas to reflect the change
fig.canvas.draw()

Note: In my previous code, I was using a fig.savefig() call before altering the ticks to debug things and this forced the rendering and generation of default ytick labels.

在此处输入图片说明

add this line : plt.setp(ax2.get_yticklabels()[-1], visible=False)

it will make the uppermost tick label on the vertical axis of axis-2 invisible

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