How to plot in multiple subplots
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001
--
Chapters
00:00 Question
00:28 Accepted answer (Score 316)
01:19 Answer 2 (Score 96)
01:37 Answer 3 (Score 33)
02:12 Answer 4 (Score 19)
02:50 Thank you
--
Full question
https://stackoverflow.com/questions/3172...
Accepted answer links:
[image]: https://i.stack.imgur.com/2JxAs.png
[image]: https://i.stack.imgur.com/0EiUD.png
Answer 2 links:
[image]: https://i.stack.imgur.com/jMSQV.jpg
Answer 3 links:
[image]: https://i.stack.imgur.com/kvOOL.png
Answer 4 links:
[change log]: https://matplotlib.org/users/whats_new.h...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #matplotlib #seaborn #subplot
#avk47
ACCEPTED ANSWER
Score 340
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, something 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 = plt.figure()
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
Score 103
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 2)
ax[0, 0].plot(range(10), 'r') #row=0, col=0
ax[1, 0].plot(range(10), 'b') #row=1, col=0
ax[0, 1].plot(range(10), 'g') #row=0, col=1
ax[1, 1].plot(range(10), 'k') #row=1, col=1
plt.show()
ANSWER 3
Score 19
You might be interested in the fact that as of matplotlib version 2.1 the second code from the question works fine as well.
From the change log:
Figure class now has subplots method The Figure class now has a subplots() method which behaves the same as pyplot.subplots() but on an existing figure.
Example:
import matplotlib.pyplot as plt
fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)
plt.show()
ANSWER 4
Score 12
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.


