在子图中循环生成两次图表

Looping in Subplots produced charts twice

我有以下代码,正在尝试循环生成三组 2x2 图。

from IPython.display import display

def generate_subplots (i):


    fig, axs = plt.subplots(ncols=2, nrows=2, figsize = (11, 11))

    plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.3, hspace=0.3)

    p1.plot(kind='barh', ax=axs[0, 0]).invert_yaxis()
    p3.plot(kind='barh', ax=axs[0, 1]).invert_yaxis()
    p2.plot(kind='barh', ax=axs[1, 0]).invert_yaxis()
    p4.plot(kind='barh', ax=axs[1, 1]).invert_yaxis()

    axs[0, 0].set_xlim(0, 1)
    axs[0, 1].set_xlim(0, 1)
    axs[1, 0].set_xlim(0, 1)
    axs[1, 1].set_xlim(0, 1)

    axs[0, 0].set_title('Title A')
    axs[0, 1].set_title('Title B')
    axs[1, 0].set_title('Title C')
    axs[1, 1].set_title('Title D')

    display ('Users who have at least ' + str(i+1) + ' cell phones')

    display (fig)


for i in range(0, 3):

    d1 = df[df3['varx'] > i)]
    d2 = df[df3['varx'] > i)]
    d3 = df[df3['varx'] > i)]
    d4 = df[df3['varx'] > i)]

    p1 = d1.var1.value_counts(normalize=True).sort_index()
    p2 = d2.var1.value_counts(normalize=True).sort_index() 
    p3 = d3.var1.value_counts(normalize=True).sort_index() 
    p4 = d4.var1.value_counts(normalize=True).sort_index() 

    generate_subplots(i)

我尝试使用 'display' 函数,但现在它打印了两次图表集。它是这样的:

至少拥有一部手机的用户

设置 1 个 2x2 图表

拥有至少2部手机的用户

设置 2 个 2x2 图表

拥有至少3部手机的用户

设置 3 个 2x2 图表

设置 1 个 2x2 图表

设置 2 个 2x2 图表

设置 3 个 2x2 图表

我做错了什么?

我假设您在 jupyter notebook 或类似环境中工作。如果是这样,你真的不需要 display 函数。

def generate_subplots(i, p1, p2, p3, p4):
    fig, axs = plt.subplots(ncols=2, nrows=2, figsize=(11, 11))

    fig.subplots_adjust(wspace=0.3, hspace=0.3)

    for ax, p, letter in zip(axs.flat, (p1, p3, p2, p4), list('ABCD')):
        p.plot(kind='barh', ax=ax)
        ax.invert_yaxis()
        ax.set_xlim(0, 1)
        ax.set_title('Title {}'.format(letter))

    print('Users who have at least {} cell phones'.format(i))
    return fig


for i in range(0, 3):
    p_df = [
        df.loc[df['varx'] > i, 'var1'].value_counts(normalize=True)
        for df in [df1, df2, df3, df4]
    ]
    fig = generate_subplots(i, *p_df)