Search code examples
pythonfor-loopseabornsubplot

Cannot print multiple countplot charts based on different features in a loop


I am using the Titanic dataset shown below:

enter image description here

I want to create a count plot using Seaborn for a few different feature columns. Below is my attempted code:

col_list = ['sex', 'class', 'embark_town']

for i in col_list:
    print (i)
    
    feature_plot = sns.countplot(x=df[i])
    print (feature_plot)

Unfortunately, my output only produces the chart for the last column in my col_list (not the two previous ones).

enter image description here

What am I doing wrong? How can I fix this?


Solution

  • I think the problem is that seaborn plots on top of the las figure

    try to create a new figure

    col_list = ['sex', 'class', 'embark_town']
    
    for i in col_list:
        print (i)
        fig, ax = plt.subplots()
        feature_plot = sns.countplot(x=df[i], ax=ax)
        print (feature_plot)
        plt.show()