Reputation: 337
I want to assign multiple xlabels at once in matplotlib. Now I assign multiple 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 this way is redundant. Is there any way to assign multiple xlabels at once like follows?
(ax1,ax2).set_xlabel("x label")
Upvotes: 4
Views: 2133
Reputation: 3473
I would prefer a normal for
-loop, as it makes your intention clear:
for ax in [ax1, ax2]:
ax.set_xlabel("x label")
If you prefer a one-liner, remember the map
function:
map(lambda ax : ax.set_xlabel("x label"), [ax1, ax2])
Upvotes: 0
Reputation: 339340
You may use a list comprehension.
[ax.set_xlabel("x label") for ax in [ax1,ax2]]
You may also already set the labels at subplot creation, which simplifies the complete code from the question to one single line:
fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, subplot_kw=dict(xlabel="xlabel") )
Upvotes: 3
Reputation: 6863
You could store your ax
objects in a list. By using the subplots
function, 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
Upvotes: 3