我试图显示一个包含3个图的图形,每个图都是(8,1)形子图的图。
从本质上讲,我想要一个大人物,包括三个部分,每个部分包含(8,1)形子图。
我正在寻找一种无需手动设置所有比例和间距的方法。我这样做的原因是与其他三个预定义信号相比,可视化一个8通道神经信号,每个信号为8通道。
如果通过这种方式有任何意义,我正在尝试这样的(虚假代码):
fig, ax = plt.subplots(n_figures = 3, n_rows = 8, n_cols = 1)
ax[figure_i, row_j, col_k].imshow(image)
有没有办法做到这一点?
这是我所谈论的例子。理想情况下,它将是三个子图,并且在每个子图中都有一组形状为8x1的子图。我知道如何通过遍历所有边距并设置比例来将其全部绘制出来,但是我想知道是否存在一种更简单的方法,而不必完成上述示例代码中所述的所有其他代码和设置我写了。
答案 0 :(得分:0)
您可以通过首先使用 plt.subplots()
函数创建具有适当布局的子图网格,然后循环遍历轴数组以绘制数据来创建这种图形,如下例所示:
import numpy as np # v 1.19.2
import matplotlib.pyplot as plt # v 3.3.2
# Create sample signal data as a 1-D list of arrays representing 3x8 channels
signal_names = ['X1', 'X2', 'X3']
nsignals = len(signal_names) # ncols of the subplot grid
nchannels = 8 # nrows of the subplot grid
nsubplots = nsignals*nchannels
x = np.linspace(0, 14*np.pi, 100)
y_signals = nsubplots*[np.cos(x)]
# Set subplots width and height
subp_w = 10/nsignals # 10 corresponds the figure width in inches
subp_h = 0.25*subp_w
# Create figure and subplot grid with the appropriate layout and dimensions
fig, axs = plt.subplots(nchannels, nsignals, sharex=True, sharey=True,
figsize=(nsignals*subp_w, nchannels*subp_h))
# Optionally adjust the space between the subplots: this can also be done by
# adding 'gridspec_kw=dict(wspace=0.1, hspace=0.3)' to the above function
# fig.subplots_adjust(wspace=0.1, hspace=0.3)
# Loop through axes to create plots: note that the list of axes is transposed
# in this example to plot the signals one after the other column-wise, as
# indicated by the colors representing the channels
colors = nsignals*plt.get_cmap('tab10').colors[:nchannels]
for idx, ax in enumerate(axs.T.flat):
ax.plot(x, y_signals[idx], c=colors[idx])
if ax.is_first_row():
ax.set_title(signal_names[idx//nchannels], pad=15, fontsize=14)
plt.show()