我有以下内容:
import matplotlib.pyplot as plt
fig = plt.figure()
for i in range(10):
ax = fig.add_subplot(551 + i)
ax.plot([1,2,3,4,5], [10,5,10,5,10], 'r-')
我在想象 55 意味着它正在创建一个宽度为 5 个子图且深度为 5 个子图的网格 - 所以可以容纳 25 个子图吗?
for 循环只会迭代 10 次 - 所以我认为(显然是错误的)25 个可能的图可以容纳这些迭代,但我得到以下结果:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-118-5775a5ea6c46> in <module>()
10
11 for i in range(10):
---> 12 ax = fig.add_subplot(551 + i)
13 ax.plot([1,2,3,4,5], [10,5,10,5,10], 'r-')
14
/home/blah/anaconda/lib/python2.7/site-packages/matplotlib/figure.pyc in add_subplot(self, *args, **kwargs)
1003 self._axstack.remove(ax)
1004
-> 1005 a = subplot_class_factory(projection_class)(self, *args, **kwargs)
1006
1007 self._axstack.add(key, a)
/home/blah/anaconda/lib/python2.7/site-packages/matplotlib/axes/_subplots.pyc in __init__(self, fig, *args, **kwargs)
62 raise ValueError(
63 "num must be 1 <= num <= {maxn}, not {num}".format(
---> 64 maxn=rows*cols, num=num))
65 self._subplotspec = GridSpec(rows, cols)[int(num) - 1]
66 # num - 1 for converting from MATLAB to python indexing
ValueError: num must be 1 <= num <= 30, not 0
请您参考如下方法:
在方便的速记符号中,55 表示有 5 行和 5 列。然而,速记符号仅适用于个位数整数(即 nrows、ncols 和 plot_number 均小于 10)。
您可以将其扩展为完整符号(即使用逗号:add_subplot(nrows, ncols, plot_number))然后一切都适合您:
for i in range(10):
ax = fig.add_subplot(5, 5, 1 + i)
ax.plot([1,2,3,4,5], [10,5,10,5,10], 'r-')
来自 plt.subplot 的文档(它使用与 fig.add_subplot 相同的参数):
Typical call signature:
subplot(nrows, ncols, plot_number)Where nrows and ncols are used to notionally split the figure into nrows * ncols sub-axes, and plot_number is used to identify the particular subplot that this function is to create within the notional grid. plot_number starts at 1, increments across rows first and has a maximum of nrows * ncols.
In the case when nrows, ncols and plot_number are all less than 10, a convenience exists, such that the a 3 digit number can be given instead, where the hundreds represent nrows, the tens represent ncols and the units represent plot_number.
