Seaborn相比Matplotlib有什么优势?如何使用?
中等机器学习
答题要点
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# 设置Seaborn样式
sns.set_theme(style='whitegrid') # darkgrid/whitegrid/dark/white/ticks
sns.set_palette('husl') # 调色板
# 加载示例数据
tips = sns.load_dataset('tips')
iris = sns.load_dataset('iris')
# 1. 分布图
sns.histplot(tips['total_bill'], bins=20, kde=True) # 带核密度估计的直方图
plt.title('账单分布')
plt.show()
# 2. 箱线图
sns.boxplot(x='day', y='total_bill', data=tips, palette='Set2')
plt.title('每天账单箱线图')
plt.show()
# 3. 小提琴图(结合箱线图和密度图)
sns.violinplot(x='day', y='total_bill', data=tips, hue='sex', split=True)
plt.title('小提琴图')
plt.show()
# 4. 散点图
sns.scatterplot(x='total_bill', y='tip', data=tips, hue='smoker',
style='time', size='size', sizes=(20, 200))
plt.title('账单与小费散点图')
plt. show()
# 5. 回归图
sns.regplot(x='total_bill', y='tip', data=tips, scatter_kws={'alpha':0.5})
plt.title('账单与小费回归')
plt.show()
# 6. 分类散点图
sns.stripplot(x='day', y='total_bill', data=tips, jitter=True, alpha=0.5)
plt.show()
# 7. 分组柱状图
sns.barplot(x='day', y='total_bill', hue='sex', data=tips, ci=95)
# ci: 置信区间
plt.show()
# 8. 计数图
sns.countplot(x='day', hue='sex', data=tips)
plt.title('每天数量')
plt.show()
# 9. 点图
sns.pointplot(x='day', y='total_bill', hue='sex', data=tips)
plt.show()
# 10. 联合分布图
sns.jointplot(x='total_bill', y='tip', data=tips, kind='reg')
# kind: scatter/reg/hist/hex/kde
plt.show()
# 11. 成对关系图
sns.pairplot(iris, hue='species', diag_kind='kde')
plt.show()
# 12. 热力图
corr = tips.corr()
sns.heatmap(corr, annot=True, fmt='.2f', cmap='coolwarm',
center=0, square=True, linewidths=1)
plt.title('相关系数热力图')
plt.show()
# 13. 分面图
g = sns.FacetGrid(tips, col='time', row='smoker', margin_titles=True)
g.map(sns.scatterplot, 'total_bill', 'tip')
plt.show()
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题