我有以下代码,并试图遍历以生成三组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)
我尝试使用“显示”功能,但现在它两次打印图表集。它是这样的:
拥有至少1部手机的用户
设置1个2x2图表
至少拥有2部手机的用户
设置2张2x2图表
至少拥有3部手机的用户
设置3张2x2图表
设置1个2x2图表
设置2张2x2图表
设置3张2x2图表
我在做什么错了?
答案 0 :(得分:1)
我假设您在Jupyter笔记本电脑或类似环境中工作。如果是这样,您实际上就不需要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)