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



当我绘制我的熊猫系列的密度分布时,我使用

.plot(kind='kde')

是否有可能得到这个图的输出值?如果是,如何做到这一点?我需要绘制的值

没有.plot(kind='kde')的输出值,它返回一个axes对象。

图中matplotlib.lines.Line2D对象的_x_y方法可获取原始值

In [266]:
ser = pd.Series(np.random.randn(1000))
ax=ser.plot(kind='kde')
In [265]:
ax.get_children() #it is the 3nd object
Out[265]:
[<matplotlib.axis.XAxis at 0x85ea370>,
 <matplotlib.axis.YAxis at 0x8255750>,
 <matplotlib.lines.Line2D at 0x87a5a10>,
 <matplotlib.text.Text at 0x8796f30>,
 <matplotlib.text.Text at 0x87a5850>,
 <matplotlib.text.Text at 0x87a56d0>,
 <matplotlib.patches.Rectangle at 0x87a56f0>,
 <matplotlib.spines.Spine at 0x85ea5d0>,
 <matplotlib.spines.Spine at 0x85eaed0>,
 <matplotlib.spines.Spine at 0x85eab50>,
 <matplotlib.spines.Spine at 0x85ea3b0>]
In [264]:
#get the values
ax.get_children()[2]._x
ax.get_children()[2]._y

您也可以直接调用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

上面的答案不适合我。下面的代码为我工作。

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

最新更新