【问题标题】:How to plot a list of figures in a single subplot?如何在单个子图中绘制数字列表?
【发布时间】:2021-04-26 11:50:30
【问题描述】:

我有 2 个数字列表及其轴。 我需要将每个图绘制在一个子图中,以便这些图成为一个大子图。我该怎么做?

我尝试了 for 循环,但它不起作用。

这是我尝试过的:

import ruptures as rpt
import matplotlib.pyplot as plt

# make random data with 100 samples and 9 columns 
n_samples, n_dims, sigma = 100, 9, 2
n_bkps = 4
signal, bkps = rpt.pw_constant(n_samples, n_dims, n_bkps, noise_std=sigma)

figs, axs = [], []
for i in range(signal.shape[1]):
    points = signal[:,i]
    # detection of change points 
    algo = rpt.Dynp(model='l2').fit(points)
    result = algo.predict(n_bkps=2)
    fig, ax = rpt.display(points, bkps, result, figsize=(15,3))
    figs.append(fig)
    axs.append(ax)
    plt.show()

【问题讨论】:

  • 请编辑您的问题以包含minimal reproducible example,以便更轻松地为您提供帮助。 these 的任何例子有帮助吗?
  • @importrandom 请检查问题。我已经添加了代码并改写了我的问题。我检查了这些示例,但没有一个有帮助。
  • @Mr.T 我想从列表中提取数字并将它们放在一个子图中,例如link
  • 这在matplotlib tutorials 中有很好的解释。在this example 中,您会看到如何使用循环接近轴。如果您遇到任何与您的代码相关的特定问题,请提出其他问题。
  • @Mr.T 这个例子并不是我想要的。在该示例中,x 和 y 可用,因此使用 for 循环很容易绘制图形。但就我而言,我无法访问 x 或 y,因为这些数字是从几个库中生成的(即 heliopy 和破裂)。我只有一个数字列表和另一个相应轴选项的列表。

标签: python python-3.x matplotlib plot figure


【解决方案1】:

我查看了source code of ruptures.display(),它接受传递给 matplotlib 的 **kwargs。这允许我们将输出重定向到单个图形,并且使用 gridspec,我们可以在该图形中定位各个子图:

import ruptures as rpt
import matplotlib.pyplot as plt

n_samples, n_dims, sigma = 100, 9, 2
n_bkps = 4
signal, bkps = rpt.pw_constant(n_samples, n_dims, n_bkps, noise_std=sigma)

#number of subplots
n_subpl = signal.shape[1]
#give figure a name to refer to it later
fig = plt.figure(num = "ruptures_figure", figsize=(8, 15))
#define grid of nrows x ncols
gs = fig.add_gridspec(n_subpl, 1)


for i in range(n_subpl):
    points = signal[:,i]
    algo = rpt.Dynp(model='l2').fit(points)
    result = algo.predict(n_bkps=2)
    #rpt.display(points, bkps, result)
    #plot into predefined figure
    _, curr_ax = rpt.display(points, bkps, result, num="ruptures_figure")
    #position current subplot within grid
    curr_ax[0].set_position(gs[i].get_position(fig))
    curr_ax[0].set_subplotspec(gs[i])   

plt.show()

样本输出:

【讨论】:

  • 这正是我的意思。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 2020-04-08
  • 2020-11-10
  • 2022-07-11
  • 2021-01-03
相关资源
最近更新 更多