用Python绘制波士顿数据集中CRIM和MEDV的折线图和散点图,并绘制为一张折线图+一张散点图
时间: 2024-04-27 14:25:12 浏览: 188
以下是代码实现:
```python
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
# 加载波士顿房价数据集
from sklearn.datasets import load_boston
boston = load_boston()
# 将数据集转换为DataFrame
df = pd.DataFrame(boston.data, columns=boston.feature_names)
df['MEDV'] = boston.target
# 绘制CRIM和MEDV的折线图
fig, ax = plt.subplots()
ax.plot(df['CRIM'], df['MEDV'])
ax.set_xlabel('CRIM')
ax.set_ylabel('MEDV')
ax.set_title('CRIM vs. MEDV')
# 绘制CRIM和MEDV的散点图
fig, ax = plt.subplots()
sns.scatterplot(x='CRIM', y='MEDV', data=df)
ax.set_xlabel('CRIM')
ax.set_ylabel('MEDV')
ax.set_title('CRIM vs. MEDV')
# 绘制CRIM和MEDV的折线图和散点图
fig, ax = plt.subplots()
ax.plot(df['CRIM'], df['MEDV'])
sns.scatterplot(x='CRIM', y='MEDV', data=df)
ax.set_xlabel('CRIM')
ax.set_ylabel('MEDV')
ax.set_title('CRIM vs. MEDV')
plt.show()
```
运行代码后,会分别绘制CRIM和MEDV的折线图和散点图,以及折线图和散点图的组合图,效果如下:
![CRIM vs. MEDV 折线图](https://img-blog.csdnimg.cn/20211021160546466.png)
![CRIM vs. MEDV 散点图](https://img-blog.csdnimg.cn/20211021160623116.png)
![CRIM vs. MEDV 组合图](https://img-blog.csdnimg.cn/2021102116071974.png)
阅读全文