如何获取pandas .plot(kind='kde')的输出
当我绘制我的 pandas Series 的密度分布图时,我使用了
.plot(kind='kde')
那么,能不能得到这个图的输出值呢?如果可以的话,应该怎么做?我需要绘制出来的数值。
3 个回答
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
9
你也可以直接使用 scipy.stats.gaussian_kde()
这个函数,这在 pandas 的源代码中就是这么做的:
https://github.com/pydata/pandas/blob/master/pandas/tools/plotting.py#L284
这个函数的说明文档在这里:
http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html
15
.plot(kind='kde')
会返回一个Axes
对象。- 在这个图表中,可以通过
_x
和_y
方法来获取原始数值,这些方法属于matplotlib.lines.Line2D
对象。- 可以使用
ax.get_children()
来检查,确认matplotlib.lines.Line2D
是否在[0]
位置。 - 从技术上讲,
._y
和._x
是“私有”方法,具体内容可以参考 对象名称前面单下划线和双下划线的含义是什么?
- 可以使用
- 在
python 3.12.0
、pandas 2.1.1
和matplotlib 3.8.0
中测试过
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')
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)