读取EXCEL的两列数据,绘制直方图叠加正态曲线到一张图上,并计算两条曲线重合率
时间: 2024-12-10 15:50:32 浏览: 118
在Python中,你可以使用pandas库来处理Excel文件的数据,matplotlib库用于绘制图形,以及scipy库来计算概率密度函数并估计正态分布。首先,你需要安装必要的库:
```bash
pip install pandas matplotlib scipy openpyxl
```
以下是一个简单的步骤说明如何完成这个任务:
1. **导入所需的库**:
```python
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import norm
from openpyxl import load_workbook
```
2. **加载Excel数据**:
```python
# 加载Excel文件
excel_file = load_workbook('your_file.xlsx')
sheet_name = 'Sheet1' # 更改为你实际的工作表名称
data = pd.read_excel(excel_file, sheet_name)
col1 = data['Column1'] # 替换为你的第一列数据所在的列名
col2 = data['Column2'] # 替换为你的第二列数据所在的列名
```
3. **数据预处理** (假设列1和列2都是数值型):
```python
col1_values = col1.dropna() # 删除缺失值
col2_values = col2.dropna()
```
4. **绘制直方图和正态曲线**:
```python
fig, ax1 = plt.subplots()
ax2 = ax1.twinx() # 创建第二个y轴
ax1.hist(col1_values, bins='auto', alpha=0.5, label='Column 1')
ax2.plot(col1_values, norm.pdf(col1_values), color='red', linewidth=2, label='Normal Curve for Column 1')
# 绘制第二列数据的直方图和正态曲线
ax1.hist(col2_values, bins='auto', alpha=0.5, density=True, label='Column 2')
ax2.plot(col2_values, norm.pdf(col2_values, loc=col1_values.mean(), scale=col1_values.std()), color='blue', linewidth=2, label='Normal Curve for Column 2')
# 添加标签、标题和图例
ax1.set_xlabel('Values')
ax1.set_ylabel('Frequency', color='black')
ax2.set_ylabel('Probability Density', color='red')
plt.title('Histogram with Normal Curves Overlay')
plt.legend(loc='upper right')
# 计算两条曲线重合率
intersection_area = np.sum(np.minimum(norm.pdf(col1_values, loc=col1_values.mean(), scale=col1_values.std()),
norm.pdf(col2_values, loc=col2_values.mean(), scale=col2_values.std()))) * np.diff(ax2.get_xlim())[0]
total_area_column1 = np.trapz(norm.pdf(col1_values, loc=col1_values.mean(), scale=col1_values.std()), col1_values)
total_area_column2 = np.trapz(norm.pdf(col2_values, loc=col2_values.mean(), scale=col2_values.std()), col2_values)
overlap_rate = intersection_area / (total_area_column1 + total_area_column2)
print(f"Overlap rate between the two normal curves: {overlap_rate}")
```
5. **显示图表**:
```python
plt.show()
```
现在你应该看到了直方图和两条正态曲线的叠加图,以及两条曲线的重合率。
阅读全文