如何删除colorbar冗余X轴刻度?cax.set_xticks([])无效
问题描述
老师提供的代码生成的colorbar显示正常:
fig, ax = plt.subplots( 1, 4, figsize=[18, 4], sharex=True, sharey=True, ) for i in range(4): ax[i].imshow(np.random.rand(200, 800), cmap="viridis_r", origin="lower") divider = make_axes_locatable(ax[-1]) cax = divider.new_horizontal(size="4%", pad="2%") fig.add_axes(cax) fig.colorbar(mpl.cm.ScalarMappable(cmap=mpl.cm.viridis_r, norm=norm), cax=cax) plt.show()
但在自己的另一段代码中,colorbar出现带有密集刻度的冗余X轴,尝试使用cax.set_xticks([])无法去除该轴,请问该如何解决?
解决方法
直接隐藏X轴元素:
比起仅清空刻度,直接把整个X轴设为不可见更彻底:cax.xaxis.set_visible(False)明确指定colorbar方向:
若使用垂直colorbar,创建时显式声明orientation="vertical",避免matplotlib自动判断出错:fig.colorbar(mpl.cm.ScalarMappable(cmap=mpl.cm.viridis_r, norm=norm), cax=cax, orientation="vertical")关闭cax的轴共享:
主图的sharex=True可能导致colorbar轴被意外共享,创建cax时手动关闭共享:cax = divider.new_horizontal(size="4%", pad="2%", sharex=False)彻底清空刻度定位器:
若仍有残留刻度,清空主、次刻度的定位器:cax.xaxis.set_major_locator(plt.NullLocator()) cax.xaxis.set_minor_locator(plt.NullLocator())
内容的提问来源于stack exchange,提问作者Firestar-Reimu
相关产品推荐
相关产品推荐

