如何获取pandas .plot(kind='kde')的输出?

7
当我绘制pandas Series的密度分布图时,我使用以下代码:
.plot(kind='kde')

这个图形的输出数值是否可以获取?如果可以,如何获取?我需要绘制出来的数值。

3个回答

15
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


1
这正是我所需要的。ax.get_children() 对我来说是个重大突破。我不知道你可以这样做。 - O.rka
孩子们的顺序改变了,我有过这样的经历。你能叫他们的名字/具体点吗? - Nicole Goebel

9

相关的Pandas代码已经移至https://github.com/pandas-dev/pandas/blob/0.21.x/pandas/plotting/_core.py#L1381-L1430。 - shadowtalker

0

对我来说,最佳答案不起作用。 以下代码适用于我。

xx = s.plot.density(color='orange', bw_method=0.1, alpha=1)
hist_x = xx.lines[0]._x
hist_y = xx.lines[0]._y

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接