问题
Sometimes I come across code such as this:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
fig = plt.figure()
fig.add_subplot(111)
plt.scatter(x, y)
plt.show()
Which produces:
I\'ve been reading the documentation like crazy but I can\'t find an explanation for the 111
. sometimes I see a 212
.
What does the argument of fig.add_subplot()
mean?
回答1:
These are subplot grid parameters encoded as a single integer. For example, "111" means "1x1 grid, first subplot" and "234" means "2x3 grid, 4th subplot".
Alternative form for add_subplot(111)
is add_subplot(1, 1, 1)
.
回答2:
I think this would be best explained by the following picture:

To initialize the above, one would type:
import matplotlib.pyplot as plt
fig = plt.figure()
fig.add_subplot(221) #top left
fig.add_subplot(222) #top right
fig.add_subplot(223) #bottom left
fig.add_subplot(224) #bottom right
plt.show()
回答3:
The answer from Constantin is spot on but for more background this behavior is inherited from Matlab.
The Matlab behavior is explained in the Figure Setup - Displaying Multiple Plots per Figure section of the Matlab documentation.
subplot(m,n,i) breaks the figure window into an m-by-n matrix of small subplots and selects the ithe subplot for the current plot. The plots are numbered along the top row of the figure window, then the second row, and so forth.
回答4:
My solution is
fig = plt.figure()
fig.add_subplot(1, 2, 1) #top and bottom left
fig.add_subplot(2, 2, 2) #top right
fig.add_subplot(2, 2, 4) #bottom right
plt.show()
回答5:
import matplotlib.pyplot as plt
plt.figure(figsize=(8,8))
plt.subplot(3,2,1)
plt.subplot(3,2,3)
plt.subplot(3,2,5)
plt.subplot(2,2,2)
plt.subplot(2,2,4)
The first code creates the first subplot in a layout that has 3 rows and 2 columns.
The three graphs in the first column denote the 3 rows. The second plot comes just below the first plot in the same column and so on.
The last two plots have arguments (2, 2)
denoting that the second column has only two rows, the position parameters move row wise.
回答6:
fig.add_subplot(ROW,COLUMN,POSITION)
- ROW=number of rows
- COLUMN=number of columns
- POSITION= position of the graph you are plotting
Examples
`fig.add_subplot(111)` #There is only one subplot or graph
`fig.add_subplot(211)` *and* `fig.add_subplot(212)`
There are total 2 rows,1 column therefore 2 subgraphs can be plotted. Its location is 1st. There are total 2 rows,1 column therefore 2 subgraphs can be plotted.Its location is 2nd
来源:https://stackoverflow.com/questions/3584805/in-matplotlib-what-does-the-argument-mean-in-fig-add-subplot111