所有子图的等轴标签和范围 [英] Equal axis labels and ranges for all subplots

查看:45
本文介绍了所有子图的等轴标签和范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Say I'm plotting an image with 4 subplots like so:

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

正如您所看到的,子图中唯一发生变化的是最后一行(即:绘制的内容),但轴的标签和范围保持不变.

As you can see the only thing that changes among subplots is the last line (ie: what's being plotted) but the axis' labels and ranges stay the same.

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

How can I set the axis labels and ranges once and have it apply to all my subplots?

推荐答案

use 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()
    ...: 

这篇关于所有子图的等轴标签和范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆