I am trying to share a y label across a subplot's rows, unique to the rows. Not the same y label across all rows. Additionally, I want a general approach, not one where you label it individually for each row: rather store the labels and assign them to the relevant row using some loop (or through a better approach, I know very little about coding).
Below is a generalisation of the relevant part of my code. Here there are 2 rows, 3 columns. Ideally the dimensions of the array of the object for "axs" are decided beforehand and there is a general approach to that too, but I'm trying to keep this focused on just getting the y labelling fixed. I want a shared y label across row 1, "A", and shared y label, "B", across row 2, both on the outer left.
import matplotlib.pyplot as plt
x = [0, 1]
y = [0, 1]
fig, axs = plt.subplots(2, 3)
axs[0, 0].plot(x, y, 'b')
axs[0, 1].plot(x, y, 'b')
axs[0, 2].plot(x, y, 'b')
axs[1, 0].plot(x, y, 'r')
axs[1, 1].plot(x, y, 'r')
axs[1, 2].plot(x, y, 'r')
label = ["Row 1", "Row 2"]
for j in range(0, 2):
axs[j, :].set_ylabel('{}'.format(label[j]))
The following error I receive is from the line: "axs[j, :].set_ylabel('{}'.format(label[j]))": AttributeError: 'numpy.ndarray' object has no attribute 'set_ylabel'
I wouldn't be surprised if I'm making a mistake with the dimensions or type of variable somewhere.
Apologies if this is poorly described, again I'm no coder. I will amend the question to make it more clear if needed.
CodePudding user response:
There may be many ways to do this, but I think we can just set the axs and labels using the zip function.
for l,ax in zip(label, axs):
print(ax)
ax[0].set_ylabel(l)
#axs[j, :].set_ylabel('{}'.format(label[j]))
[<AxesSubplot:> <AxesSubplot:> <AxesSubplot:>]
[<AxesSubplot:> <AxesSubplot:> <AxesSubplot:>]