所有子图的等轴标签和范围

时间:2014-02-25 15:15:35

标签: python matplotlib

假设我正在绘制一个包含4个子图的图像,如下所示:

import matplotlib.pyplot as plt
fig = plt.figure()

ax1 = fig.add_subplot(221)
plt.xlim(0, 10)
plt.ylim(0, 20)
plt.xlabel('Label_x')
plt.ylabel('Label_y')
plt.plot(something_1)

ax2 = fig.add_subplot(222)
plt.xlim(0, 10)
plt.ylim(0, 20)
plt.xlabel('Label_x')
plt.ylabel('Label_y')
plt.plot(something_2)

ax3 = fig.add_subplot(223)
plt.xlim(0, 10)
plt.ylim(0, 20)
plt.xlabel('Label_x')
plt.ylabel('Label_y')
plt.plot(something_3)

ax4 = fig.add_subplot(224)
plt.xlim(0, 10)
plt.ylim(0, 20)
plt.xlabel('Label_x')
plt.ylabel('Label_y')
plt.plot(something_4)

plt.show()

正如您所看到的那样,子图之间唯一的变化是最后一行(即:正在绘制的是什么),但轴的标签和范围保持不变。

如何设置轴标签和范围一次并将其应用于我的所有子图?

2 个答案:

答案 0 :(得分:3)

使用plt.subplots

In [36]: import matplotlib.pyplot as plt
    ...: fig, axes=plt.subplots(2, 2)
    ...: for ax in axes.ravel(): #ravel axes to a flattened array 
    ...:     ax.set_xlim(0, 10)
    ...:     ax.set_ylim(0, 20)
    ...:     ax.set_xlabel('Label_x')
    ...:     ax.set_ylabel('Label_y')
    ...: plt.show()
    ...: 

答案 1 :(得分:0)

我知道这是一段时间前发布的,但是对于现在看到此帖子的任何人,我都会添加到@zhangxaochen的答案中,以注意到在plt.subplots命令中还具有参数sharex和{{1 }}。因此,如果需要,您可以使用:

sharey
相关问题