Is there a way to assign multiple xlabels at once in matplotlib?

I want to assign several xlabels to matplotlib at once. Now I assign a few xlabels as follows.

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

I feel that this method is superfluous. Is there a way to assign multiple xlabels at once, as shown below?

(ax1,ax2).set_xlabel("x label")
+4
source share
3 answers

You can use list comprehension.

[ax.set_xlabel("x label") for ax in [ax1,ax2]]

You can also set labels when creating a subtask, which simplifies the complete code from the question to one line:

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

You can save your objects axin a list. Using the function subplots, this list is created for you:

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
+3
source

for -loop, :

for ax in [ax1, ax2]:
    ax.set_xlabel("x label")

, map:

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

Source: https://habr.com/ru/post/1681276/


All Articles