Matplotlib:如何在没有实际标签的情况下 hide/remove 标记 Colorbar?

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

我目前有一个 Colorbar 标签太多:

我几乎只需要第一个和最后一个标签,因此想删除所有其他标签。常见的答案是 [label.set_visible(False) for label in ax.xaxis.get_ticklabels()],但 ax.xaxis.get_ticklabels() 对我来说没有任何内容。我怎样才能设置 whatever-is-printed-anyways 不可见?我的(缩写)代码:

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')

您的 ax.xaxis.get_ticklabels() 没有任何适合您的原因是因为您的颜色栏是垂直的。您可以调整代码并通过明确指定位置来仅指定所需的刻度标签。下面的代码可能对您有所帮助,

# 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

小说明: 在这里,custom_ticks 是您刻度的位置。垂直方向,-1 是最低点,1 是最高点。正如您所说,您几乎只需要这两个,现在您可以在此代码的最后一行指定它们,您就大功告成了。