简体   繁体   中英

Matplotlib: How to hide/remove ticks of Colorbar when it has no actual labels?

I currently have a Colorbar with too many labels:

颜色标签太多

I pretty much only need the first and last labels, and therefore want to remove all the others. The common answer is to simply [label.set_visible(False) for label in ax.xaxis.get_ticklabels()] , but ax.xaxis.get_ticklabels() does not contain anything for me. How can I set whatever-is-printed-anyways invisible? My (abbreviated) code:

fig, ax = plt.subplots(1, 1, figsize=(10, 10))

cmap = plt.cm.jet
cmaplist = [cmap(i) for i in range(cmap.N)]
cmap = mpl.colors.LinearSegmentedColormap.from_list('Custom cmap', cmaplist, cmap.N)
bounds = np.linspace(0, numColors, numColors+1)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

tags = [], [], []
for i, list in enumerate(listPerColor):
    tags += [i] * len(list)

plt.scatter(xs, ys, c=tags, cmap=cmap, norm=norm)

ax = fig.add_axes([0.9, 0.125, 0.03, 0.7552])
cb = mpl.colorbar.ColorbarBase(ax, cmap=cmap, norm=norm, spacing='proportional',
                               ticks=bounds+0.5, boundaries=bounds, format='%1i')
cb.ax.set_ylabel('Generation', size=12)
plt.savefig('graph.pdf')

The reason why your ax.xaxis.get_ticklabels() did not have anything for you is because your colorbar is vertical. You could tweak your code and specify only the required tick labels by specifying them explicitly with locations. The code below might help you,

# your code as it is
ax = fig.add_axes([0.9, 0.125, 0.03, 0.7552])
custom_ticks = [-1, 1]

# changed the ticks parameter to the above variable
cb = mpl.colorbar.ColorbarBase(ax, cmap=cmap, norm=norm, spacing='proportional',
                               ticks=custom_ticks, boundaries=bounds, format='%1i')

# set the labels to their ticks
# assuming numColors is your upper label and 0 is your lower label
cb.ax.set_yticklabels([0, numColors])

#your code as it goes

Little Explanation: Here, the custom_ticks is the position of your ticks. Vertically, -1 is the lowest point and 1 is the highest point. And as you said you pretty much need only those two, you can now specify them in the last line of this code and you are pretty much done.

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