如何在Python中绘制100%堆积面积的facetgrid?

2024-09-30 10:39:52 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我用很长的代码做的。在

enter image description here

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

enter image description here

这是代码中的交叉表。在

enter image description here

这就是除法后的样子。在

但我必须在代码中做两次,因为我需要一个图来表示存活=0,一个表示存活=1。在


如何用更少的代码实现同样的效果?我觉得制作子图非常愚蠢,然后一个接一个地绘制和定制它们。


Tags: 代码truedffigsetaxistitanicddf
1条回答
网友
1楼 · 发布于 2024-09-30 10:39:52

您可以将轴设置为一个列表,使用列表理解来设置ddf_Pclass_Sex数组,然后循环它们(以减少对xlabel、xticks和set title的重复调用)。否则我觉得你需要打电话给其他人

fig, axs = plt.subplots(1, 2, figsize=[7,2], sharex=True, sharey=True)
ddf_Pclass_Sex = [pd.crosstab(titanic_df[titanic_df.Survived == i].Pclass, 
                              titanic_df[titanic_df.Survived == i].Sex) for i in range(2)]

for i, d, axs in enumerate(zip(ddf_Pclass_Sex, axs)):
    d.divide(d.sum(axis=1), axis=0).plot.area(stacked=True, 
                                              ax=ax, 
                                              color=['#55A868', '#4C72B0'])
    ax.set_title('Survived = ' + str(i), fontsize=9.5)
    ax.set_xlabel('')
    ax.set_xticks(np.arange(1, 4, 1))

ax[0].set_ylabel('Percent (%)')
leg = axs[1].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)
plt.show()

抱歉,没有数据帧无法运行。根据我的经验,最好是把代码保持得像以前那样。即使它更长,当你以后需要调整时,它也会变得更容易;所有的东西都是明确的,如果你想在两个图中有所不同,可以很容易地改变事情。在

相关问题 更多 >

    热门问题