Python 在保留网格的同时删除 x 轴刻度(matplotlib)

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

Remove the x-axis ticks while keeping the grids (matplotlib)

pythonmatplotlib

提问by DurgaDatta

I want to remove the ticks on the x-axis but keep the vertical girds. When I do the following I lose both x-axis ticks as well as the grid.

我想删除 x 轴上的刻度,但保留垂直网格。当我执行以下操作时,我会同时丢失 x 轴刻度和网格。

import matplotlib.pyplot as plt
fig = plt.figure() 
figr = fig.add_subplot(211)
...
figr.axes.get_xaxis().set_visible(False)
figr.xaxsis.grid(True)

How can I retain the grid while makeing x-axis ticks invisible?

如何在使 x 轴刻度不可见的同时保留网格?

采纳答案by mgilson

By remove the ticks, do you mean remove the tick labels or the ticks themselves? This will remove the labels:

删除刻度是指删除刻度标签还是刻度本身?这将删除标签:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 100)

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(x, np.sin(x))

ax.grid(True)
ax.set_xticklabels([])


plt.show()


If you really want to get rid of the little tick lines, you can add this:

如果您真的想摆脱小刻度线,可以添加以下内容:

for tic in ax.xaxis.get_major_ticks():
    tic.tick1On = tic.tick2On = False

You could turn the tick labelsoffhere too without resorting to the ax.set_xticklabels([])"hack" by setting tic.label1On = tic.label2On = False:

您也可以此处关闭刻度标签而无需ax.set_xticklabels([])通过设置tic.label1On = tic.label2On = False

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 100)

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(x, np.sin(x))

ax.grid(True)
for tic in ax.xaxis.get_major_ticks():
    tic.tick1On = tic.tick2On = False
    tic.label1On = tic.label2On = False

plt.show()