使用python读取excel中的某几列数据并绘制正态分布直方图与核密度图
时间: 2023-11-27 14:50:22 浏览: 100
首先,需要安装以下库:pandas、matplotlib、seaborn、numpy
然后,可以按照以下步骤进行操作:
1. 导入所需的库
```python
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
```
2. 读取Excel文件中的数据
```python
df = pd.read_excel('data.xlsx', usecols=['列1', '列2', '列3'])
```
3. 绘制直方图
```python
plt.hist(df['列1'], bins=20, density=True, alpha=0.5, color='blue')
plt.hist(df['列2'], bins=20, density=True, alpha=0.5, color='green')
plt.hist(df['列3'], bins=20, density=True, alpha=0.5, color='red')
plt.xlabel('数据')
plt.ylabel('频率')
plt.title('正态分布直方图')
plt.show()
```
4. 绘制核密度图
```python
sns.kdeplot(df['列1'], shade=True, color='blue')
sns.kdeplot(df['列2'], shade=True, color='green')
sns.kdeplot(df['列3'], shade=True, color='red')
plt.xlabel('数据')
plt.ylabel('密度')
plt.title('核密度图')
plt.show()
```
完整代码如下:
```python
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
df = pd.read_excel('data.xlsx', usecols=['列1', '列2', '列3'])
plt.hist(df['列1'], bins=20, density=True, alpha=0.5, color='blue')
plt.hist(df['列2'], bins=20, density=True, alpha=0.5, color='green')
plt.hist(df['列3'], bins=20, density=True, alpha=0.5, color='red')
plt.xlabel('数据')
plt.ylabel('频率')
plt.title('正态分布直方图')
plt.show()
sns.kdeplot(df['列1'], shade=True, color='blue')
sns.kdeplot(df['列2'], shade=True, color='green')
sns.kdeplot(df['列3'], shade=True, color='red')
plt.xlabel('数据')
plt.ylabel('密度')
plt.title('核密度图')
plt.show()
```
阅读全文
相关推荐


















