Python 在 matplotlib 颜色栏中隐藏每个第 n 个刻度标签的最干净方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20337664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cleanest way to hide every nth tick label in matplotlib colorbar?
提问by David Shean
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)


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.
我发现的大多数示例都将用户指定的字符串列表传递给 cbar.set_ticklabels()。我正在寻找一个通用的解决方案。
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.
我知道使用定位器对象必须有一种干净的方法来做到这一点。
采纳答案by HYRY
For loop the ticklabels, and call set_visible():
For 循环刻度标签,并调用set_visible():
for label in cbar.ax.xaxis.get_ticklabels()[::2]:
label.set_visible(False)
回答by Jacob Scherffenberg-M?ller
Just came across this thread, nice answers. I was looking for a way to hide every tick between the nth ticks. And found the enumerate function. So if anyone else is looking for something similar you can do it like this.
刚刚遇到这个线程,很好的答案。我正在寻找一种方法来隐藏第 n 个刻度之间的每个刻度。并找到了枚举函数。因此,如果其他人正在寻找类似的东西,您可以这样做。
for index, label in enumerate(ax.xaxis.get_ticklabels()):
if index % n != 0:
label.set_visible(False)
回答by malla
One-liner for those who are into that!
为那些喜欢它的人准备的单线!
n = 7 # Keeps every 7th label
[l.set_visible(False) for (i,l) in enumerate(ax.xaxis.get_ticklabels()) if i % n != 0]
回答by Ben
I use the following to show every 7th x label:
我使用以下内容显示每 7 个 x 标签:
plt.scatter(x, y)
ax = plt.gca()
temp = ax.xaxis.get_ticklabels()
temp = list(set(temp) - set(temp[::7]))
for label in temp:
label.set_visible(False)
plt.show()
It's pretty flexible, as you can do whatever you want instead of plt.scatter. Hope it helps.
它非常灵活,因为你可以做任何你想做的事情,而不是 plt.scatter。希望能帮助到你。

