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()
这会产生:
我已经疯狂地阅读文档,但是我找不到说明111
的解释。有时我看到212
。
fig.add_subplot()
的参数意味着什么?
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()
这会产生:
我已经疯狂地阅读文档,但是我找不到说明111
的解释。有时我看到212
。
fig.add_subplot()
的参数意味着什么?
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()
这些是以单个整数编码的子图网格参数。例如,“111”表示“1x1网格,第一个子图”,“234”表示“2x3网格,第四个子图”。
add_subplot(111)
的另一种形式是 add_subplot(1, 1, 1)
。
subplot(m,n,i)将图形窗口分成一个m×n的小子图矩阵,并选择第i个子图作为当前绘图。图形沿着窗口的上一行编号,然后是第二行,依此类推。
add_subplot() 方法有几种调用方式:
add_subplot(nrows, ncols, index, **kwargs)
add_subplot(pos, **kwargs)
add_subplot(ax)
add_subplot()
<-- 自3.1.0版本以来第一次和第二次调用实现了相同的功能(在下面解释的限制范围内)。可以将它们看作首先使用前两个数字指定网格布局(2x2、1x8、3x4等),例如:
f.add_subplot(3,4,1)
# is equivalent to:
f.add_subplot(341)
#!/usr/bin/env python3
import matplotlib.pyplot as plt
def plot_and_text(axis, text):
'''Simple function to add a straight line
and text to an axis object'''
axis.plot([0,1],[0,1])
axis.text(0.02, 0.9, text)
f = plt.figure()
f2 = plt.figure()
_max = 12
for i in range(_max):
axis = f.add_subplot(3,4,i+1, fc=(0,0,0,i/(_max*2)), xticks=[], yticks=[])
plot_and_text(axis,chr(i+97) + ') ' + '3,4,' +str(i+1))
# If this check isn't in place, a
# ValueError: num must be 1 <= num <= 15, not 0 is raised
if i < 9:
axis = f2.add_subplot(341+i, fc=(0,0,0,i/(_max*2)), xticks=[], yticks=[])
plot_and_text(axis,chr(i+97) + ') ' + str(341+i))
f.tight_layout()
f2.tight_layout()
plt.show()
通过在左侧使用调用 1,您可以返回任何轴对象;然而,在右侧使用调用 2时,您只能返回索引最多为9的轴对象,这使得子图j),k)和l)无法使用此调用访问。
即它阐明了这一点来自文档:
pos是一个三位数的整数,其中第一位是行数,第二位是列数,第三位是子图的索引。例如,fig.add_subplot(235)与fig.add_subplot(2, 3, 5)相同。 请注意,所有整数都必须小于10才能使用此形式。
在极少数情况下, add_subplot 可以被调用只传入一个参数,此时该参数应为一个子图axes实例,该实例已经在当前图形中创建,但未出现在图形的axes列表中。
如果没有传递位置参数,则默认为(1,1,1)。
也就是说,重现问题中的调用 fig.add_subplot(111)
。这基本上设置了一个1×1的子图网格,并返回网格中第一个(也是唯一的)轴对象。
fig.add_subplot(ROW,COLUMN,POSITION)
示例
`fig.add_subplot(111)` #There is only one subplot or graph
`fig.add_subplot(211)` *and* `fig.add_subplot(212)`
总共有2行,1列,因此可以绘制2个子图。它的位置是第1个。总共有2行,1列,因此可以绘制2个子图。它的位置是第2个。
fig.add_subplot(111)
就像 fig.add_subplot(1, 1, 1)
,其中的数字111
表示子图网格参数,但编码为单个整数。
要在一个n*m网格中选择第k个子图,可以这样做:fig.add_subplot(n, m, k)
。
1.5.0
版本中不支持),这似乎只适用于Matlab。(请注意,在Matplotlib中还有其他选项可以实现此行为,例如gridspec) - lab