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

后端 未结 3 738
心在旅途
心在旅途 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条回答
  •  梦毁少年i
    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)
    

提交回复
热议问题