循环数据帧以并排打印2 countplot

2024-04-26 19:14:09 发布

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

我试图编写一个函数来循环遍历选定的列,并绘制countplot的子图,但它只绘制其中一个图,并且给出一条错误消息“AxesSubplot”对象不支持索引。但是这些代码适用于直方图

提前感谢你的帮助

def subplot_countplot(dataframe, list_of_columns, list_of_titles, list_of_xlabels):
    fig, ax = plt.subplots(ncols=2, figsize=(16,8))
    for i, column in enumerate(list_of_columns):
        ax = sns.countplot(x=dataframe[column], data=marital)
        ax[i].set_title(list_of_titles[i], fontsize=12)
        ax[i].set_xlabel(list_of_xlabels[i], fontsize=12)
        ax[i].set_ylabel('Number of Marriages', fontsize=12)
        
        plt.show()

*#Barcharts for trends in marriages*

list_of_columns = ['yearoflatestmarriage','monthoflatestmarriage']
list_of_titles = ['Year of Marriage','Month of Marriage']
list_of_xlabels=['Count of Marriage' for i in list_of_columns]

subplot_countplot(marital, list_of_columns, list_of_titles, list_of_xlabels)

list_of_columns = ['yearoflatestmarriage','monthoflatestmarriage']
list_of_titles = ['Year of Marriage','Month of Marriage']
list_of_xlabels=['Count of Marriage' for i in list_of_columns]

subplot_countplot(marital, list_of_columns, list_of_titles, list_of_xlabels)