matplotlib:将 AxesSubplot 实例添加到图中

matplotlib: Add AxesSubplot instances to a figure

我要疯了...这应该是一个简单的练习,但我卡住了:

我有一个 Jupyter notebook,我正在使用 ruptures Python package. All I want to do is, take the figure or AxesSubplot(s) that the display() 函数 returns 并将其添加到我自己的图形中,这样我就可以共享 x 轴、拥有单个图像等.:

import pandas as pd
import matplotlib.pyplot as plt

myfigure = plt.figure()
l = len(df.columns)
    
for index, series in enumerate(df):
        
    data = series.to_numpy().astype(int)

    algo = rpt.KernelCPD(kernel='rbf', min_size=4).fit(data)
    result = algo.predict(pen=3)

    myfigure.add_subplot(l, 1, index+1)
    rpt.display(data, result)

    plt.title(series.name)

    
plt.show()

我得到的是一个带有所需子图数量的图(全部为空)和 nruptures:

分开的图

当我想要子图填充数字时...

我基本上不得不重新创建 ruptures.display(data,result) 产生的情节,以获得我想要的数字:

import pandas as pd
import numpy as np
import ruptures as rpt
import matplotlib.pyplot as plt
from matplotlib.ticker import EngFormatter

fig, axs = plt.subplots(len(df.columns), figsize=(22,20), dpi=300)

for index, series in enumerate(df):
    
    resampled = df[series].dropna().resample('6H').mean().pad()
    data = resampled.to_numpy().astype(int)
    
    algo = rpt.KernelCPD(kernel='rbf', min_size=4).fit(data)
    result = algo.predict(pen=3)
    
    # Create ndarray of tuples from the result
    result = np.insert(result, 0, 0) # Insert 0 as first result
    tuples = np.array([ result[i:i+2] for i in range(len(result)-1) ])
    
    ax = axs[index]
    
    # Fill area beween results alternating blue/red
    for i, tup in enumerate(tuples):
        if i%2==0:
            ax.axvspan(tup[0], tup[1], lw=0, alpha=.25)
        else:
            ax.axvspan(tup[0], tup[1], lw=0, alpha=.25, color='red')
    
    ax.plot(data)
    ax.set_title(series)
    ax.yaxis.set_major_formatter(EngFormatter())


plt.subplots_adjust(hspace=.3)
plt.show()

我在这上面浪费的时间多得我无法证明,但现在天气很好,今晚我可以睡个好觉了:D