【问题标题】:How to make facetgrid of 100% stacked area plot in Python?如何在 Python 中制作 100% 堆叠面积图的 facetgrid?
【发布时间】:2017-09-21 01:26:41
【问题描述】:

这是我用很长的代码制作的。

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

这是代码中的交叉表。

这是除法后的样子。

但我必须在我的代码中制作 2 次,因为我需要一个用于 Survived = 0 的绘图和一个用于 Survived = 1 的绘图。


如何用更少的代码达到同样的效果?我觉得自己做子图很傻,一个一个地绘制和自定义。

【问题讨论】:

    标签: python matplotlib data-visualization seaborn


    【解决方案1】:

    您可以将轴设置为列表,使用列表推导来设置 ddf_Pclass_Sex 数组,然后循环遍历它们(以减少对 xlabel、xticks 和设置标题的重复调用)。否则我认为您需要调用其他所有内容,

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

    抱歉,没有数据框就无法运行。根据我的经验,实际上最好让代码更像你以前的样子。即使它更长,它也会让您以后需要调整时更容易;一切都是明确的,如果你想要两个情节的差异,可以很容易地改变事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多