matplotlib 计算2D KDE绘图的面积

deyfvvtc  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(80)

我有一个DataFrame格式的数据,它有两列,一个x列和一个y列,我用以下方式将数据输入sns. kdeplut:sns.kdeplot(data = data ,x="x", y="y", fill=True, common_norm=False, alpha=0.7,color=color)并得到一个有几个层的图,我想计算图的面积,这意味着该区域的轮廓将是最低密度,因为它是最大的区域,只有该层
我试过从图中获取水平,但它返回None,而不是给我一个数字列表(我假设这是几个水平的输出)
示例代码:

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 100)
y = x**2

data = {"X": x, "Y": y}

kde_plot =sns.kdeplot(data=data,x="X",y="Y", common_norm=False, color='blue')
levels = kde_plot.collections[0].get_array()
print(levels)

plt.title('2D KDE Plot with Custom Data')
plt.xlabel('X')
plt.ylabel('Y')

plt.show()

如果有更有效的方法来计算面积,我将非常感谢输入

xmjla07d

xmjla07d1#

我提取最外面的轮廓路线,它反映了最低密度的轮廓,然后用SciPy的simps函数计算这条曲线下的面积。

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.integrate import simps

# Generate example data
x = np.linspace(0, 10, 100)
y = x**2
data = {"X": x, "Y": y}

# Create the KDE plot
kde_plot = sns.kdeplot(data=data, x="X", y="Y", fill=True, common_norm=False, color='blue')

# Extract the contour levels
contour_collections = kde_plot.collections
outermost_contour = contour_collections[-1]

# Extract the contour paths
contour_paths = outermost_contour.get_paths()

# Extract the vertices of the outermost contour
vertices = contour_paths[0].vertices

# Separate the x and y values
x_values, y_values = vertices[:, 0], vertices[:, 1]

# Calculate the area under the curve using the trapezoidal rule
area_outline = simps(y_values, x=x_values)

print("Area of the outline (lowest density):", area_outline)

plt.title('2D KDE Plot with Custom Data')
plt.xlabel('X')
plt.ylabel('Y')

plt.show()

这将提供最外轮廓面积的更准确估计。
输出:

相关问题