Pandas Series Histogram - How make subplots show up on separate graphs?

I am trying out the Titanic ML competition on Kaggle, and want to try to plot histograms of two separate pieces of information, on two separate histograms. However, the code below plots everything on one histogram, as seen in the picture below (blue being cb, and orange being qt).

For reference, the datatype of cb and qt is matplotlib.axes._subplots.AxesSubplot.

Is there a way I can get cb and qt to be on two separate histograms? Thank you in advance!

cb = cherbourg.loc[cherbourg.Survived == 1].Pclass.hist()
cb.set_ylabel('No. Survivors')
cb.set_title('Number of Survivors From Cherbourg By SES')

qt = queenstown.loc[queenstown.Survived == 1].Pclass.hist()

enter image description here

1 answer

  • answered 2020-08-11 00:43 Trenton McKinney

    • Select the unique towns and plot them
    • Histogram is not the correct type of plot. These are categorical value_counts.
    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    # load the dataframe
    df = sns.load_dataset('titanic')
    # set the column to a Categorical type: optional
    df.pclass = pd.Categorical(df.pclass, categories=[1, 2, 3], ordered=True)
    # plot
    for town in df.embark_town.unique():
        data = df[(df.embark_town == town) & df.survived == 1]
        if not data.empty:
            plt.figure(figsize=(6, 3))
            plt.ylabel('No. Survivors')
            plt.title(f'Number of Survivors From {town}')

    enter image description here


    • Specify row='embark_town' instead of col='embark_town' to have a single column of plots
    • Using seaborn.countplot
    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    # select data
    df = sns.load_dataset('titanic')
    data = df[df.survived == 1]
    # plot
    g = sns.FacetGrid(data, col='embark_town', height=5), 'pclass', order=[1, 2, 3])
    g.set_axis_labels(x_var='Pclass', y_var='No. Survivors')

    enter image description here