【问题标题】:Is there a way in python using matplotlib to create a figure with subplots of subplots?python中有没有办法使用matplotlib来创建一个带有子图的子图?
【发布时间】:2020-04-11 17:41:56
【问题描述】:

我正在尝试显示一个包含 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 的子图。我了解如何通过所有边距和设置比例来绘制这一切,但我想知道是否有更简单的方法可以做到这一点,而不必通过上面示例代码中描述的所有附加代码和设置我写过。

【问题讨论】:

  • 我认为引用的副本为您提供了原始问题中的多个子图,并且答案有助于您的页面布局。如果没有,请在此处发表澄清评论,我会重新打开。
  • 不幸的是,引用的副本没有回答我的问题,因为我正在寻找子图中的子图。例如,在引用的重复项的已接受答案中,图中有一张 4x4 子图的图片。如果有一种方法可以在每个 4x4 子图中绘制一个 8x1 子图,而无需专门手动添加更多子图,然后调整边距以使其看起来像是三个单独的数字连接在一起,那么这将回答我的问题。跨度>
  • 在我看来,您只是想在一个图中绘制多组数据,而不是制作单独的子图。
  • 也许你可以画出你想要的情节并在此处上传为图片?
  • @Arne 我已经添加了我正在谈论的内容的草图。我正在寻找一种方法来做到这一点,而不必修改所有尺寸和间距,也不必单独绘制每个图表进行比较。

标签: python matplotlib


【解决方案1】:

您可以通过首先使用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()

【讨论】:

    猜你喜欢
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 2020-07-14
    相关资源
    最近更新 更多