我有以下几点:
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-')
Run Code Online (Sandbox Code Playgroud)
我在想象这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
Run Code Online (Sandbox Code Playgroud)
在 convience 速记符号中,the55确实表示有 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-')
Run Code Online (Sandbox Code Playgroud)
来自plt.subplot( 使用与 相同的参数fig.add_subplot)的文档:
典型的调用签名:
Run Code Online (Sandbox Code Playgroud)subplot(nrows, ncols, plot_number)其中 nrows 和 ncols 用于在概念上将图形拆分为 nrows * ncols 子轴,而 plot_number 用于标识此函数将在概念网格内创建的特定子图。plot_number 从 1 开始,首先跨行递增,最大为 nrows * ncols。
在 nrows、ncols 和 plot_number 都小于 10 的情况下,存在一个便利,例如可以给出一个 3 位数字,其中数百代表 nrows,十位代表 ncols,单位代表 plot_number。
尽管汤姆回答了您的问题,但在这种情况下您应该使用fig, axs = plt.subplots(n, m). 这将创建一个包含子图的n行和m列的新图形。 fig是创建的图形。 axs是一个 2D numpy 数组,其中数组中的每个元素都是图中相应位置的子图。所以右上角的元素axs是图中右上角的子图。您可以通过正常索引访问子图,或循环它们。
所以在你的情况下你可以这样做
import matplotlib.pyplot as plt
# axs is a 5x5 numpy array of axes objects
fig, axs = plt.subplots(5, 5)
# "ravel" flattens the numpy array without making a copy
for ax in axs.ravel():
ax.plot([1,2,3,4,5], [10,5,10,5,10], 'r-')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11593 次 |
| 最近记录: |