绘制多个 matplotlib 轴 class 对象

Plotting multiple matplotlib axes class object

我的问题如下:我试图以可读的方式绘制 6 个不同的设计矩阵。 为这个设计矩阵创建显示的函数是 nipy 模块的一部分,描述如下:

class nipy.modalities.fmri.design_matrix.DesignMatrix

Function show(): Visualization of a design matrix

Parameters:

 rescale: bool, optional, 
      rescale columns magnitude for visualization or not.
 ax: axis handle, optional
      Handle to axis onto which we will draw design matrix.
 cmap: colormap, optional
      Matplotlib colormap to use, passed to imshow.

Returns:

 ax: axis handle

基本上,我正在尝试用 6 个不同的矩阵制作一个 3 行 2 列的子图。

n_scans = 84
tr = 7
hrf_models = ['canonical', 'canonical with derivative', 'fir', 'spm', 'spm_time', 'spm_time_dispersion']
drift_model = 'cosine'
frametimes = np.arange(0, n_scans * tr,tr)
hfcut = 128

fig1 = plt.figure()

ax1 = fig1.add_subplot(3, 2, 1)
hrf_model = hrf_models[0]
design_matrix = make_dmtx(frametimes, paradigm, hrf_model=hrf_model, drift_model=drift_model, hfcut=hfcut)
ax1 = design_matrix.show()
ax1.set_position([.05, .25, .9, .65])
ax1.set_title('Design matrix with {} as hrf_model'.format(hrf_model))

ax2 = fig1.add_subplot(3, 2, 2)
hrf_model = hrf_models[1]
design_matrix = make_dmtx(frametimes, paradigm, hrf_model=hrf_model, drift_model=drift_model, hfcut=hfcut)
ax2 = design_matrix.show()
ax2.set_position([.05, .25, .9, .65])
ax2.set_title('Design matrix with {} as hrf_model'.format(hrf_model))

......

ax6 = fig1.add_subplot(3, 2, 6)
hrf_model = hrf_models[5]
design_matrix = make_dmtx(frametimes, paradigm, hrf_model=hrf_model, drift_model=drift_model, hfcut=hfcut)
ax6 = design_matrix.show()
ax6.set_position([.05, .25, .9, .65])
ax6.set_title('Design matrix with {} as hrf_model'.format(hrf_model))

plt.show()

目前输出的是一个3行2列的图形,上面有空白图形,然后下面分别显示每个设计矩阵。

此外,循环列表 hrf_models 比重复同一块 6 次要好得多。我在某个时候做了,但遗憾的是输出完全一样。

当前输出(需要滚动查看所有设计矩阵):

感谢您的帮助!

基本上,您在问题中输入的文档字符串的摘录已经告诉您解决方案。您需要对 DesignMatrix.show()

使用 ax 参数
ax1 = fig1.add_subplot(3, 2, 1)
design_matrix = make_dmtx(...)
design_matrix.show(ax = ax1)

要使用循环,您可以先生成所有轴,然后循环遍历它们。

fig, axes = plt.subplots(nrows=3,ncols=2)
for i, ax in enumerate(axes.flatten()):
    hrf_model = hrf_models[0]
    design_matrix = make_dmtx(frametimes, paradigm, hrf_model=hrf_models[i], 
                              drift_model=drift_model, hfcut=hfcut)
    design_matrix.show(ax = ax)

请注意,我没有在这里测试任何东西,因为我没有可用的 nipy。