在matplotlib中动态添加具有多个列的子图 [英] Dynamically add subplots in matplotlib with more than one column
问题描述
如果我使用多个列来显示我的子图,我如何动态地将新图添加到一堆子图?
如您所见,这并没有给我想要的东西.第一个图占用了所有列,其他图都小于应有的
('2.7.6 | 64位|(默认,2014年9月15日,17:36:35)[MSC v.1500 64位(AMD64)]'
我还有 matplotlib 1.4.3 版:
将matplotlib导入为mpl打印 mpl.__version__1.4.3
我在下面尝试了Paul的答案,并收到以下错误消息:
导入数学导入matplotlib.pyplot作为plt从 matplotlib 导入 gridspecdef do_plot(ax):ax.plot([1,2,3], [4,5,6], 'k.')N = 11cols = 3行 = math.ceil(N/cols)gs = gridspec.GridSpec(行,列)无花果= plt.figure()对于范围(N)中的n:ax = fig.add_subplot(gs[n])do_plot(ax)fig.tight_layout()---------------------------------------------------------------------------TypeError Traceback(最近一次通话)<ipython-input-1-f74203b1c1bf>在< module>()中15 fig = plt.figure()16 表示范围内的 n(N):--->17轴= fig.add_subplot(gs [n])18 do_plot(ax)19C:\Users\user\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\figure.pyc in add_subplot(self, *args, **kwargs)962(self)__ axstack.remove(ax)963->964 a = subplot_class_factory(projection_class)(self, *args, **kwargs)965第966章死了(二更)C:\Users\user\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axes\_subplots.pyc in __init__(self, fig, *args, **kwargs)73 引发 ValueError('Illegal argument(s) to subplot: %s' % (args,))74--->75 self.update_params()7677#_axes_class在subplot_class_factory中设置C:\Users\user\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axes\_subplots.pyc in update_params(self)113 self.figbox,self.rowNum,self.colNum,self.numRows,self.numCols = 114 self.get_subplotspec().get_position(self.figure,->第 115 回116117 def is_first_col():C:\ Users \ user \ AppData \ Local \ Enthought \ Canopy \ User \ lib \ site-packages \ matplotlib \ gridspec.pyc在get_position(self,fig,return_all)中423424 figBottoms, figTops, figLefts, figRights = -->425 gridspec.get_grid_positions(fig)426427C:\ Users \ user \ AppData \ Local \ Enthought \ Canopy \ User \ lib \ site-packages \ matplotlib \ gridspec.pyc在get_grid_positions中(自己,图)103 cellHeights = [netHeight*r/tr for r in self._row_height_ratios]其他104条:->105 cellHeights = [cellH] *排数106107 sepHeights = [0] +([sepH] *(nrows-1))TypeError:无法将序列乘以'float'类型的非整数
假定网格的至少1个维数和总图数已知,我将使用 gridspec
模块和一点有点数学.
导入数学导入matplotlib.pyplot作为plt从matplotlib导入gridspecdef do_plot(ax):ax.plot([1,2,3], [4,5,6], 'k.')N = 11列数 = 3行= int(math.ceil(N/cols))gs = gridspec.GridSpec(rows, cols)无花果= plt.figure()对于范围(N)中的n:ax = fig.add_subplot(gs [n])do_plot(ax)fig.tight_layout()
How can I dynamically add a new plot to bunch of subplots if I'm using more than one column to display my subplots? This answers this question for one column, but I cant seem to modify the answers there to make it dynamically add to a subplot with x
columns
I modified Sadarthrion's answer and attempted the following. Here, for sake of an example, I made number_of_subplots=11
and num_cols = 3
.
import matplotlib.pyplot as plt
def plotSubplots(number_of_subplots,num_cols):
# Start with one
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3])
for j in range(number_of_subplots):
if j > 0:
# Now later you get a new subplot; change the geometry of the existing
n = len(fig.axes)
for i in range(n):
fig.axes[i].change_geometry(n+1, num_cols, i+1)
# Add the new
ax = fig.add_subplot(n+1, 1, n+1)
ax.plot([4,5,6])
plt.show()
plotSubplots(11,3)
As you can see this isn't giving me what I want. The first plot takes up all the columns and the additional plots are smaller than they should be
EDIT:
('2.7.6 | 64-bit | (default, Sep 15 2014, 17:36:35) [MSC v.1500 64 bit (AMD64)]'
Also I have matplotlib version 1.4.3:
import matplotlib as mpl
print mpl.__version__
1.4.3
I tried Paul's answer below and get the following error message:
import math
import matplotlib.pyplot as plt
from matplotlib import gridspec
def do_plot(ax):
ax.plot([1,2,3], [4,5,6], 'k.')
N = 11
cols = 3
rows = math.ceil(N / cols)
gs = gridspec.GridSpec(rows, cols)
fig = plt.figure()
for n in range(N):
ax = fig.add_subplot(gs[n])
do_plot(ax)
fig.tight_layout()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-f74203b1c1bf> in <module>()
15 fig = plt.figure()
16 for n in range(N):
---> 17 ax = fig.add_subplot(gs[n])
18 do_plot(ax)
19
C:\Users\user\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\figure.pyc in add_subplot(self, *args, **kwargs)
962 self._axstack.remove(ax)
963
--> 964 a = subplot_class_factory(projection_class)(self, *args, **kwargs)
965
966 self._axstack.add(key, a)
C:\Users\user\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axes\_subplots.pyc in __init__(self, fig, *args, **kwargs)
73 raise ValueError('Illegal argument(s) to subplot: %s' % (args,))
74
---> 75 self.update_params()
76
77 # _axes_class is set in the subplot_class_factory
C:\Users\user\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axes\_subplots.pyc in update_params(self)
113 self.figbox, self.rowNum, self.colNum, self.numRows, self.numCols = 114 self.get_subplotspec().get_position(self.figure,
--> 115 return_all=True)
116
117 def is_first_col(self):
C:\Users\user\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\gridspec.pyc in get_position(self, fig, return_all)
423
424 figBottoms, figTops, figLefts, figRights = --> 425 gridspec.get_grid_positions(fig)
426
427
C:\Users\user\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\gridspec.pyc in get_grid_positions(self, fig)
103 cellHeights = [netHeight*r/tr for r in self._row_height_ratios]
104 else:
--> 105 cellHeights = [cellH] * nrows
106
107 sepHeights = [0] + ([sepH] * (nrows-1))
TypeError: can't multiply sequence by non-int of type 'float'
Assuming at least 1 dimension of your grid and the total number of plots is known, I would use the gridspec
module and a little bit of math.
import math
import matplotlib.pyplot as plt
from matplotlib import gridspec
def do_plot(ax):
ax.plot([1,2,3], [4,5,6], 'k.')
N = 11
cols = 3
rows = int(math.ceil(N / cols))
gs = gridspec.GridSpec(rows, cols)
fig = plt.figure()
for n in range(N):
ax = fig.add_subplot(gs[n])
do_plot(ax)
fig.tight_layout()
这篇关于在matplotlib中动态添加具有多个列的子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!