获取 KDE 图中轴的最大值

问题描述 投票:0回答:1

在对我的数据框进行一些处理后,我得到了以下 df(我做了

final_df.to_csv()
,这是保存的文件:

kilometers
1072.1995482049733
2503.2499069986962
354.0418359911766
858.2197121707121
872.7067362778436
1110.8656962113155
1956.1799725414431
298.5388710676759
933.9980032255144
844.663104277453

因此,如果我想获得概率密度函数(pdf),我使用

pandas.dataframe.plot.kde
获得以下图:

ploti = final_df.plot.kde()
ploti

获取 pdf 并绘制它:

from scipy import stats
import seaborn as sns

data = final_df['kilometers']
loc = data.mean()
scale = data.std()
pdf = stats.norm.pdf(data, loc=loc, scale=scale)


fig, ax = plt.subplots()
ax = sns.lineplot(x=data, y=pdf, ax=ax)
plt.show()

现在我的问题是: 有没有办法获得这些地块的最高值(其中 max 是)(假设 x 和 y,虽然只有 x 很好)?我一直在查看 getting values on x axis 和一些 matplotlib 文档(about axis in here)。我尝试了一些

ax.get_children()
ref)但没有任何用处。数据应该在 x 和 y 轴上(在理论上,据我所知,但它可能只是指情节在物理上具有的内容,而不是数据):遵循此处引用的后一个问题:

ploti.get_children()

[<matplotlib.lines.Line2D at 0x7fd294de1c60>,
 <matplotlib.spines.Spine at 0x7fd294b18040>,
 <matplotlib.spines.Spine at 0x7fd294b18400>,
 <matplotlib.spines.Spine at 0x7fd294b18460>,
 <matplotlib.spines.Spine at 0x7fd294b18490>,
 <matplotlib.axis.XAxis at 0x7fd294b18070>,
 <matplotlib.axis.YAxis at 0x7fd294b18bb0>,
 Text(0.5, 1.0, ''),
 Text(0.0, 1.0, ''),
 Text(1.0, 1.0, ''),
 <matplotlib.legend.Legend at 0x7fd294de16f0>,
 <matplotlib.patches.Rectangle at 0x7fd294b1b280>]

ploti.get_children()[5] #this one should have what I'm looking for

<matplotlib.axis.XAxis at 0x7fd294b18070>

ploti.get_children()[5]._x

AttributeError: 'XAxis' object has no attribute '_x'

我想:嘿,也许检查这个对象有什么属性,所以也许有一些“get_x_value”。但是我找不到与我正在寻找的东西相关的任何东西(我也可能缺乏知识):

dir(ploti.get_children()[5])

(我可以发布输出,但它又长又冗长。请随时索取!)

除了我认为我可以使用的:numpy 转换绘图的所有值并获取轴的最大值;有没有一种快速的方法来获得图中轴的最大值?

python pandas dataframe matplotlib probability-density
1个回答
1
投票

您可以通过以下方式获取数据:

data = ax.lines[0].get_xydata()

然后用

np.where
得到最大y的坐标:

data[np.where(data[:, 1] == max(data[:, 1]))]
© www.soinside.com 2019 - 2024. All rights reserved.