📊 Matplotlib基础
import matplotlib.pyplot as plt
import numpy as np
# 基本折线图
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.figure(figsize=(10, 6))
plt.plot(x, y, label='sin(x)', color='blue', linewidth=2)
plt.plot(x, np.cos(x), label='cos(x)', color='red', linestyle='--')
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.title('正弦和余弦函数')
plt.legend()
plt.grid(True)
plt.show()
# 保存图片
plt.savefig('plot.png', dpi=300, bbox_inches='tight')
🎨 Seaborn高级可视化
import seaborn as sns
import pandas as pd
# 设置主题
sns.set_theme(style="whitegrid")
# 加载示例数据
tips = sns.load_dataset("tips")
# 箱线图
plt.figure(figsize=(10, 6))
sns.boxplot(x="day", y="total_bill", data=tips)
plt.title("每日账单分布")
plt.show()
# 小提琴图
sns.violinplot(x="day", y="total_bill", hue="sex",
data=tips, split=True)
plt.show()
# 热力图(相关矩阵)
correlation = tips.corr(numeric_only=True)
sns.heatmap(correlation, annot=True, cmap='coolwarm')
plt.title("特征相关性")
plt.show()
# 配对图
sns.pairplot(tips, hue="sex")
plt.show()