# How do I get multiple subplots in matplotlib?

380
June 28, 2017, at 06:51 AM

I am a little confused about how this code works:

``````fig, axes = plt.subplots(nrows=2, ncols=2)
plt.show()
``````

How does the fig, axes work in this case? What does it do?

Also why wouldn't this work to do the same thing:

``````fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)
``````

Thanks

Answer 1

There are several ways to do it. The `subplots` method creates the figure along with the subplots that are then stored in the `ax` array. For example:

``````import matplotlib.pyplot as plt
x = range(10)
y = range(10)
fig, ax = plt.subplots(nrows=2,ncols=2)
for row in ax:
for col in row:
col.plot(x, y)
plt.show()
``````

However, sth. like this will also work, it's not so "clean" though since you are creating a figure with subplots and then add on top of them:

``````fig, ax = plt.subplots(nrows=2,ncols=2)
plt.subplot(2,2,1)
plt.plot(x, y)
plt.subplot(2,2,2)
plt.plot(x, y)
plt.subplot(2,2,3)
plt.plot(x, y)
plt.subplot(2,2,4)
plt.plot(x, y)
plt.show()
``````

Answer 2

read the documentation: matplotlib.pyplot.subplots

`pyplot.subplots()` returns a tuple `fig, ax` which is unpacked in two variables using the notation

``````fig, axes = plt.subplots(nrows=2, ncols=2)
``````

the code

``````fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)
``````

does not work because `subplots()`is a function in `pyplot` not a member of the object `Figure`.

POPULAR ONLINE

READ ALSO

### ElasticSearch error: [function_score] malformed query, expected [END_OBJECT] but found [FIELD_NAME]

The following JSON structure gives me an error when doing a query:

2252

### Why importing python module is considerably slower on Anaconda?

I have a python script that only imports these modules:

280

### How to print the content of a variable in python testing within a virtual environment on command line

I have a question pertaining to testing within a virtual environment on command lineI am checking if the following python code:

261

### Scrapy - ItemPipeline does not enter Process Items

I'm playing around with Scrapy, and trying to pass items generated by Spiders to an ItemPipeTHe issue is, while the pipe is entered, the actual process_items method is never called

306