bugsyb
bugsyb

Reputation: 6041

Creating Subplots in Python Matplotlib

When I'm creating subplots in Python's Maplotlib, I have to do it this way:

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)

Why, instead, doesn't the following work,

fig, ax1, ax2, ax3, ax4 = plt.subplots(nrows=2, ncols=2)

I'm trying to figure out exactly how plt.subplots. I read the documentation but I am still uncertain as to what is going on. Any help would be appreciated.

Thanks

Upvotes: 1

Views: 165

Answers (1)

Zach Fox
Zach Fox

Reputation: 614

plt.subplots() returns a tuple, (fig,axarr), where axarr is an array of axis objects. So if you have two rows and two columns, axarr is a [2,2] array of axes, but the subplots method only will return two objects, not five. This is true for any tuple, and not limited plt.subplots(). So the following will run:

a = 'banana'
b = np.array([1,2,3,4])
tup = (a,b)
fruit,(h,i,j,k) = tup

But fruit,h,i,j,k = tup will not.

Upvotes: 3

Related Questions