Search code examples
pythonpandasmatplotlibkernel-density

How to get output of pandas .plot(kind='kde')


When I plot density distribution of my pandas Series I use

.plot(kind='kde')

Is it possible to get output values of this plot? If yes how to do this? I need the plotted values.


Solution

  • import pandas as pd
    import matplotlib.pyplot as plt
    import numpy as np
    
    In [266]:
    np.random.seed(2023)  # for reproducibility 
    ser = pd.Series(np.random.randn(1000))  # or df = pd.DataFrame(np.random.randn(1000))
    ax = ser.plot(kind='kde')  # or ax = df.plot(kind='kde')
    

    enter image description here

    In [265]:
    ax.get_children() # Line2D at index 0
    Out[265]:
    [<matplotlib.lines.Line2D at 0x2b10f8322d0>,
     <matplotlib.spines.Spine at 0x2b10f7ff3e0>,
     <matplotlib.spines.Spine at 0x2b10f69a300>,
     <matplotlib.spines.Spine at 0x2b10db33a40>,
     <matplotlib.spines.Spine at 0x2b10f7ff410>,
     <matplotlib.axis.XAxis at 0x2b10f7ff530>,
     <matplotlib.axis.YAxis at 0x2b10f69a2a0>,
     Text(0.5, 1.0, ''),
     Text(0.0, 1.0, ''),
     Text(1.0, 1.0, ''),
     <matplotlib.patches.Rectangle at 0x2b104c29f40>]
    In [264]:
    # get the values
    x = ax.get_children()[0]._x
    y = ax.get_children()[0]._y
    
    plt.plot(x, y)
    

    enter image description here