如何在python中隐藏刻度标签但保持刻度到位?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20936658/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:35:14  来源:igfitidea点击:

How to hide ticks label in python but keep the ticks in place?

pythonmatplotlibaxislabels

提问by Yotam

I want to hide my ticks label on a plot I created, but keep this tick itself (the little marks on the axis). When I try to use what I've found here, for example, the entire tick is removed, and not just the labels. How can I remove only the labels then?

我想在我创建的图上隐藏我的刻度标签,但保留这个刻度本身(轴上的小标记)。例如,当我尝试使用我在此处找到的内容时,会删除整个刻度线,而不仅仅是标签。我怎样才能只删除标签呢?

采纳答案by Hooked

Set the tick labels not to be an empty array, but to be a list of empty strings. In the example below, I've replaced the xtick labels with empty strings, leaving the y axis untouched. From here you can selectively keep certain labels if you wished.

将刻度标签设置为不是空数组,而是空字符串列表。在下面的例子中,我用空字符串替换了 xtick 标签,y 轴保持不变。如果您愿意,您可以从这里有选择地保留某些标签。

import pylab as plt

fig, ax = plt.subplots()
ax.plot([1,2,3],[4,5,6])

labels = [item.get_text() for item in ax.get_xticklabels()]

empty_string_labels = ['']*len(labels)
ax.set_xticklabels(empty_string_labels)

plt.show()

enter image description here

在此处输入图片说明

This code is adapted from a previous answer.

此代码改编自以前的答案

回答by divenex

Here is a slightly simpler answer, using ax.tick_params

这是一个稍微简单的答案,使用 ax.tick_params

import matplotlib.pylab as plt

fig, ax = plt.subplots()
plt.plot([1,2,3],[4,5,6])

ax.tick_params(labelbottom=False)    

plt.show()

回答by jbplasma

I didn't find divenex's answer to work for me. This answer creates ticks without triggering any automatic labeling, hence no requirement to use "labelbottom= False":

我没有找到适合我的 Divenex 答案。此答案会在不触发任何自动标记的情况下创建刻度,因此不需要使用“labelbottom= False”:

if the bottom and left ticks already exist:

如果底部和左侧刻度已经存在:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
plt.plot([1,2,3],[4,5,6])

ax.tick_params(right= True,top= True)

if no ticks already exist:

如果没有蜱已经存在:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
plt.plot([1,2,3],[4,5,6])

ax.tick_params(right= True,top= True,left= True, bottom= True)