Python数据可视化:使用Matplotlib和Seaborn绘制鸢尾花数据集
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
from sklearn.datasets import load_iris
import seaborn as sns
# 步骤 0:数据收集
data = load_iris()
df = pd.DataFrame(data.data, columns=data.feature_names)
df['target'] = data.target
# 1. 绘制折线图 (plot)
# 图大小设置为10x5
# 分别绘制sepal length和sepal width的折线,展示它们随样本数的变化情况
# 添加标题'Sepal Length and Width Over Samples'
# 设置x轴和y轴的标签分别为'Sample Index'和'Length/Width (cm)'
# 设置图例
plt.figure(figsize=(10, 5))
plt.plot(df.index, df['sepal length (cm)'], label='Sepal Length')
plt.plot(df.index, df['sepal width (cm)'], label='Sepal Width')
plt.title('Sepal Length and Width Over Samples')
plt.xlabel('Sample Index')
plt.ylabel('Length/Width (cm)')
plt.legend()
# 2. 创建直方图 (hist)
# 设置图大小为12x8,2x2的一组子图
# 该组子图包括'sepal length', 'sepal width', 'petal length', 'petal width'属性值的直方图
# 所有子图具有相同的设置:分区数20,颜色'skyblue',透明度参数0.7
# 添加标题分别为'Histogram of Sepal length'、'Histogram of Sepal width'、'Histogram of Petal length'、'Histogram of Petal width'
# x轴分别为'Sepal length (cm)'、'Sepal width (cm)'、'Petal length (cm)'、'Petal width (cm)'
# y轴统一为'Frequency'
plt.figure(figsize=(12, 8))
plt.subplot(2, 2, 1)
plt.hist(df['sepal length (cm)'], bins=20, color='skyblue', alpha=0.7)
plt.title('Histogram of Sepal length')
plt.xlabel('Sepal length (cm)')
plt.ylabel('Frequency')
plt.subplot(2, 2, 2)
plt.hist(df['sepal width (cm)'], bins=20, color='skyblue', alpha=0.7)
plt.title('Histogram of Sepal width')
plt.xlabel('Sepal width (cm)')
plt.ylabel('Frequency')
plt.subplot(2, 2, 3)
plt.hist(df['petal length (cm)'], bins=20, color='skyblue', alpha=0.7)
plt.title('Histogram of Petal length')
plt.xlabel('Petal length (cm)')
plt.ylabel('Frequency')
plt.subplot(2, 2, 4)
plt.hist(df['petal width (cm)'], bins=20, color='skyblue', alpha=0.7)
plt.title('Histogram of Petal width')
plt.xlabel('Petal width (cm)')
plt.ylabel('Frequency')
plt.tight_layout()
plt.show()
原文地址: https://www.cveoy.top/t/topic/Rwu 著作权归作者所有。请勿转载和采集!