0

I am trying to write a function to loop through the selected columns and plot subplots of countplot but it just plots only one of the plots and also gives a error message of "AxesSubplot" object does not support indexing. But the codes work for histograms.

Appreciate the help in advance.

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)
  • `ax = sns.countplot(x=dataframe[column], data=marital)` overwrites your previously defined `ax`? I assume you mean `sns.countplot(x=dataframe[column], data=marital, ax=ax[i])`. – Mr. T Nov 10 '20 at 09:01
  • Thank you so much! Can I also ask in this codes, how and where should i add in the xticks rotation? i put it right at the bottom ```plt.xticks(rotation=45) and only the ticks on one of the graphs get rotated. – scruffiepuff Nov 10 '20 at 09:22
  • [There are several options](https://stackoverflow.com/a/56139690/8881141) how to address specific axis objects and rotate their label. I am sure you will find one that fits your purposes in this loop. Imho `ax[i].tick_params(axis="x", labelrotation=45)` is the most readable option. – Mr. T Nov 10 '20 at 09:49
  • that works brillantly!! – scruffiepuff Nov 10 '20 at 10:12
  • Great we solved this problem. But shouldn't it be `ncols=len(list_of_columns)` in your code? – Mr. T Nov 10 '20 at 10:46
  • the method u suggested here does not work though. this is the errro message "AttributeError: 'numpy.ndarray' object has no attribute 'bar' – scruffiepuff Nov 13 '20 at 07:20

0 Answers0