Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
587 views
in Technique[技术] by (71.8m points)

python - Cleanest way to hide every nth tick label in matplotlib colorbar?

The labels on my horizontal colorbar are too close together and I don't want to reduce text size further:

cbar = plt.colorbar(shrink=0.8, orientation='horizontal', extend='both', pad=0.02)
cbar.ax.tick_params(labelsize=8)

horizontal colorbar with bad labels

I'd like to preserve all ticks, but remove every other label.

Most examples I've found pass a user-specified list of strings to cbar.set_ticklabels(). I'm looking for a general solution.

I played around with variations of

cbar.set_ticklabels(cbar.get_ticklabels()[::2])

and

cbar.ax.xaxis.set_major_locator(matplotlib.ticker.MaxNLocator(nbins=4))

but I haven't found the magic combination.

I know there must be a clean way to do this using a locator object.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For loop the ticklabels, and call set_visible():

for label in cbar.ax.xaxis.get_ticklabels()[::2]:
    label.set_visible(False)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...