python 统计数据密度
时间: 2023-12-28 10:25:42 浏览: 144
以下是两种Python统计数据密度的方法:
1. 利用直方图(histogram)
```python
import matplotlib.pyplot as plt
# 读取数据
data = []
with open('data.txt', 'r') as file:
for line in file:
data.append(float(line.strip()))
# 绘制直方图
plt.hist(data, bins=10, density=True)
plt.xlabel('Value')
plt.ylabel('Density')
plt.title('Density Histogram')
plt.show()
```
2. 利用核密度估计(Kernel Density Estimation,KDE)
```python
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
# 读取数据
data = []
with open('data.txt', 'r') as file:
for line in file:
data.append(float(line.strip()))
# 生成核密度估计
kde = gaussian_kde(data)
# 生成一组用于绘制KDE曲线的数据点
x = np.linspace(min(data), max(data), 1000)
# 绘制KDE曲线
plt.plot(x, kde(x))
plt.xlabel('Value')
plt.ylabel('Density')
plt.title('Kernel Density Estimation')
plt.show()
```
阅读全文