Plotting a dataframe as both a 'hist' and 'kde' on the same plot

后端 未结 3 723
心在旅途
心在旅途 2020-12-30 07:08

I have a pandas dataframe with user information. I would like to plot the age of users as both a kind=\'kde\' and on kind=\'hist\' on

相关标签:
3条回答
  • 2020-12-30 07:30

    In case you want it for all the columns of your dataframe:

    fig, ax = plt.subplots(8,3, figsize=(20, 50)) 
    # you can change the distribution, I had 22 columns, so 8x3 is fine to me
    fig.subplots_adjust(hspace = .2, wspace=.2, )
    
    ax = ax.ravel()
    
    for i in range(len(I_df.columns)):
        ax[i] = I_df.iloc[:,i].plot(kind='hist', ax=ax[i])
        ax[i] = I_df.iloc[:,i].plot(kind='kde', ax=ax[i], secondary_y=True)
        plt.title(I_df.columns[i])
    

    I hope it helps :)

    0 讨论(0)
  • 2020-12-30 07:37

    pd.DataFrame.plot() returns the ax it is plotting to. You can reuse this for other plots.

    Try:

    ax = member_df.Age.plot(kind='kde')
    member_df.Age.plot(kind='hist', bins=40, ax=ax)
    ax.set_xlabel('Age')
    

    example
    I plot hist first to put in background
    Also, I put kde on secondary_y axis

    import pandas as pd
    import numpy as np
    
    
    np.random.seed([3,1415])
    df = pd.DataFrame(np.random.randn(100, 2), columns=list('ab'))
    
    ax = df.a.plot(kind='hist')
    df.a.plot(kind='kde', ax=ax, secondary_y=True)
    


    response to comment
    using subplot2grid. just reuse ax1

    import pandas as pd
    import numpy as np
    
    ax1 = plt.subplot2grid((2,3), (0,0))
    
    np.random.seed([3,1415])
    df = pd.DataFrame(np.random.randn(100, 2), columns=list('ab'))
    
    df.a.plot(kind='hist', ax=ax1)
    df.a.plot(kind='kde', ax=ax1, secondary_y=True)
    

    0 讨论(0)
  • 2020-12-30 07:50

    It is better and even simpler to use seaborn.displot. Prior proposed solutions had KDE plot appear a little "shifted up" for me. seaborn.distplot accurately lined up zeros between hist and kde plots.
    import seaborn as sns sns.displot(df.a)

    0 讨论(0)
提交回复
热议问题