这是我用很长的代码做的。在
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=[7,2], sharex=True, sharey=True)
ddf_Pclass_Sex0 = pd.crosstab(titanic_df[titanic_df.Survived == 0].Pclass, titanic_df[titanic_df.Survived == 0].Sex)
ddf_Pclass_Sex0.divide(ddf_Pclass_Sex0.sum(axis=1), axis=0).plot.area(stacked=True, ax=ax1, color=['#55A868', '#4C72B0'])
ax1.set_title('Survived = 0', fontsize=9.5)
ax1.legend('')
ax1.set_xlabel('')
ax1.set_ylabel('Percent (%)')
ddf_Pclass_Sex1 = pd.crosstab(titanic_df[titanic_df.Survived == 1].Pclass, titanic_df[titanic_df.Survived == 1].Sex)
ddf_Pclass_Sex1.divide(ddf_Pclass_Sex1.sum(axis=1), axis=0).plot.area(stacked=True, ax=ax2, color=['#55A868', '#4C72B0'])
ax2.set_title('Survived = 1', fontsize=9.5)
ax2.set_xlabel('')
leg = ax2.legend(fontsize='small', loc='center left', bbox_to_anchor=(1, 0.5))
leg.set_title('Sex', prop={'size':'small'})
fig.suptitle('Sex Composition in Percentage by Ticket Class', fontsize=9.5, y=1.06)
fig.text(.5, -.05, 'Ticket Class', ha='center', fontsize=9.5)
ax1.set_xticks(np.arange(1, 4, 1))
plt.show()
这是代码中的交叉表。在
这就是除法后的样子。在
但我必须在代码中做两次,因为我需要一个图来表示存活=0,一个表示存活=1。在
如何用更少的代码实现同样的效果?我觉得制作子图非常愚蠢,然后一个接一个地绘制和定制它们。
您可以将轴设置为一个列表,使用列表理解来设置ddf_Pclass_Sex数组,然后循环它们(以减少对xlabel、xticks和set title的重复调用)。否则我觉得你需要打电话给其他人
抱歉,没有数据帧无法运行。根据我的经验,最好是把代码保持得像以前那样。即使它更长,当你以后需要调整时,它也会变得更容易;所有的东西都是明确的,如果你想在两个图中有所不同,可以很容易地改变事情。在
相关问题 更多 >
编程相关推荐