首页 > 解决方案 > 如何在单个子图中绘制数字列表?

问题描述

我有 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()

在此处输入图像描述

在此处输入图像描述

标签: pythonpython-3.xmatplotlibplotfigure

解决方案


我查看了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()

样本输出:

在此处输入图像描述


推荐阅读