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

时间:2013-12-06 05:23:45

标签: python matplotlib

我想删除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)

如何在保持x轴刻度不可见的情况下保留网格?

1 个答案:

答案 0 :(得分:45)

通过删除刻度线,您的意思是删除刻度标签或刻度线本身吗?这将删除标签:

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

如果你真的想摆脱小刻度线,你可以添加:

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

您也可以turn the tick labels off来设置ax.set_xticklabels([])而无需诉诸tic.label1On = tic.label2On = False“hack”:

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