去掉所有子图的刻度标签
有没有办法在使用Matplotlib创建多个子图时完全去掉刻度标签?我现在需要根据一个更大数据集的行和列来指定每个图。我尝试过用ax.set_xticks([])和类似的y轴命令,但都没成功。
我知道想要一个没有任何坐标轴数据的图可能有点不寻常,但这正是我需要的。而且我希望这个设置能自动应用到数组中的所有子图。
5 个回答
2
你可以通过运行以下代码来去掉默认的子图x轴和y轴的刻度:
fig, ax = plt.subplots()
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
for i in range(3):
ax = fig.add_subplot(3, 1, i+1)
...
只需在fig, ax = plt.subplots()
之后添加上面提到的两行代码,就能去掉默认的刻度。
3
你可以通过以下方式去掉x轴或y轴的刻度:
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
如果你还想去掉边框,这样就完全没有坐标轴了,可以使用:
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
如果你想一次性把所有东西都去掉,可以使用:
ax.axis("off")
18
这些命令在绘制子图时也是一样的。
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
ax1.plot([1,2])
ax1.tick_params(
axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom='off', # ticks along the bottom edge are off
top='off', # ticks along the top edge are off
labelbottom='off' # labels along the bottom edge are off)
)
plt.draw()
31
比@DrV的回答还要简洁,结合了@mwaskom的评论,这是一行代码就能清除所有子图中的所有坐标轴:
# do some plotting...
plt.subplot(121),plt.imshow(image1)
plt.subplot(122),plt.imshow(image2)
# ....
# one liner to remove *all axes in all subplots*
plt.setp(plt.gcf().get_axes(), xticks=[], yticks=[]);
注意:这段代码必须在任何plt.show()
的调用之前执行。
62
你用的方法是对的。可能是你没有把 set_xticks
应用到正确的坐标轴上。
这里有个例子:
import matplotlib.pyplot as plt
import numpy as np
ncols = 5
nrows = 3
# create the plots
fig = plt.figure()
axes = [ fig.add_subplot(nrows, ncols, r * ncols + c) for r in range(0, nrows) for c in range(0, ncols) ]
# add some data
for ax in axes:
ax.plot(np.random.random(10), np.random.random(10), '.')
# remove the x and y ticks
for ax in axes:
ax.set_xticks([])
ax.set_yticks([])
这样做会得到:
注意,每个坐标轴的实例都存储在一个列表中(叫做 axes
),这样你就可以很方便地进行操作。像往常一样,有很多种方法可以做到这一点,这只是其中一个例子。