Python 有没有办法在matplotlib中一次分配多个XLabel?

Python 有没有办法在matplotlib中一次分配多个XLabel?,python,matplotlib,Python,Matplotlib,我想在matplotlib中一次分配多个XLabel。 现在我分配多个xlabel,如下所示 import matplotlib.pyplot as plt fig1 = plt.figure() ax1 = fig1.add_subplot(211) ax1.set_xlabel("x label") ax2 = fig1.add_subplot(212) ax2.set_xlabel("x label") 我觉得这种方式是多余的。 有没有办法一次分配多个xlabel,如下所示 (ax1,

我想在matplotlib中一次分配多个XLabel。 现在我分配多个xlabel,如下所示

import matplotlib.pyplot as plt

fig1 = plt.figure()
ax1 = fig1.add_subplot(211)
ax1.set_xlabel("x label")
ax2 = fig1.add_subplot(212)
ax2.set_xlabel("x label")
我觉得这种方式是多余的。 有没有办法一次分配多个xlabel,如下所示

(ax1,ax2).set_xlabel("x label")

您可以使用列表

[ax.set_xlabel("x label") for ax in [ax1,ax2]]
您可能已经在创建子批次时设置了标签,这将问题的完整代码简化为一行:

fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, subplot_kw=dict(xlabel="xlabel") )

您可以将
ax
对象存储在列表中。通过使用
子批次
功能,将为您创建以下列表:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=1, ncols=2)

[ax.set_xlabel("x label") for ax in axes]

axes[0,0].plot(data)        # whatever you want to plot

我更喜欢正常的
for
-循环,因为它清楚地表明了您的意图:

for ax in [ax1, ax2]:
    ax.set_xlabel("x label")
如果您喜欢单行程序,请记住
map
函数:

map(lambda ax : ax.set_xlabel("x label"), [ax1, ax2])

非常感谢你!