导入内置数据集iris,根据最后一列品种,将数据集分为三组,分别对三个品种的花萼长度,花萼宽度,花瓣长度,和花瓣宽度均绘制分组箱线图,每个品种采用不同的颜色显示,并修改横坐标名称为品种,纵坐标名称为测量值,标题为不同品种花朵特征的比较。(采用两种方法,常规绘图boxplot和ggplot绘图
时间: 2024-04-17 14:26:43 浏览: 126
您可以使用以下代码来实现您的需求:
```python
import seaborn as sns
import matplotlib.pyplot as plt
# 导入内置数据集iris
iris = sns.load_dataset('iris')
# 分组绘制箱线图 - 常规绘图boxplot
plt.figure(figsize=(10, 6))
sns.boxplot(x='species', y='sepal_length', data=iris, palette='Set3')
plt.xlabel('品种')
plt.ylabel('测量值')
plt.title('不同品种花朵特征的比较 - 花萼长度')
plt.show()
plt.figure(figsize=(10, 6))
sns.boxplot(x='species', y='sepal_width', data=iris, palette='Set3')
plt.xlabel('品种')
plt.ylabel('测量值')
plt.title('不同品种花朵特征的比较 - 花萼宽度')
plt.show()
plt.figure(figsize=(10, 6))
sns.boxplot(x='species', y='petal_length', data=iris, palette='Set3')
plt.xlabel('品种')
plt.ylabel('测量值')
plt.title('不同品种花朵特征的比较 - 花瓣长度')
plt.show()
plt.figure(figsize=(10, 6))
sns.boxplot(x='species', y='petal_width', data=iris, palette='Set3')
plt.xlabel('品种')
plt.ylabel('测量值')
plt.title('不同品种花朵特征的比较 - 花瓣宽度')
plt.show()
```
```python
# 分组绘制箱线图 - ggplot绘图
import pandas as pd
from plotnine import ggplot, aes, geom_boxplot
# 修改iris数据集的列名
iris.columns = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species']
# 绘制花萼长度的箱线图
p1 = ggplot(iris, aes(x='species', y='sepal_length', fill='species')) + geom_boxplot()
p1 = p1 + labs(x='品种', y='测量值', title='不同品种花朵特征的比较 - 花萼长度')
print(p1)
# 绘制花萼宽度的箱线图
p2 = ggplot(iris, aes(x='species', y='sepal_width', fill='species')) + geom_boxplot()
p2 = p2 + labs(x='品种', y='测量值', title='不同品种花朵特征的比较 - 花萼宽度')
print(p2)
# 绘制花瓣长度的箱线图
p3 = ggplot(iris, aes(x='species', y='petal_length', fill='species')) + geom_boxplot()
p3 = p3 + labs(x='品种', y='测量值', title='不同品种花朵特征的比较 - 花瓣长度')
print(p3)
# 绘制花瓣宽度的箱线图
p4 = ggplot(iris, aes(x='species', y='petal_width', fill='species')) + geom_boxplot()
p4 = p4 + labs(x='品种', y='测量值', title='不同品种花朵特征的比较 - 花瓣宽度')
print(p4)
```
这样,您就可以使用常规绘图boxplot和ggplot绘图两种方法绘制三个品种的花萼长度、花萼宽度、花瓣长度和花瓣宽度的分组箱线图,并且每个品种采用不同的颜色显示。同时,横坐标名称为品种,纵坐标名称为测量值,标题为不同品种花朵特征的比较。
阅读全文
相关推荐


















