0

I have created a 3x3 subplots by using the pandas df.line.plot:

ax=df.plot.line(subplots=True, grid=True,layout=(3, 3), sharex=True, legend=False,ylim=[-5,25])

It returns 3x3 matrix of Axes objects. Now I want to create a joint legend for those subplots.

As the other post suggests I should use:

handles, labels = ax.get_legend_handles_labels()
fig.legend(handles, labels, loc='upper center')

The problem is I can't use it because I have no figure created here. I only have axes. How can I make it work?

I edited the post, because I thought I could create a figure and prescribe the axes, but I guess it came from my confusion on subject.

szczor1
  • 191
  • 1
  • 2
  • 12

1 Answers1

1

You have two options:


First: Either use double indices (for row and column) as shown in the comments and then use ax[0,0], ax[0,1], ax[0,2] ... ax[2,0], ax[2,1], ax[2,2]. For 3 rows and 3 columns, the indices will run from 0 up to 2 (so 0, 1, 2)

You can also use ax[0][0] and so on. Both formats are equivalent.


Second: If you don't want to use two indices, you can flatten the ax and then use a single index as

ax = ax.flatten()

This will convert ax from 2d object to a 1-d array of 9 subfigures. Then you can use ax[0], ax[1], ax[2], ... ax[8] (9-1 because indexing starts from 0 in python)

Sheldore
  • 37,862
  • 7
  • 57
  • 71