如何使用FacetGrid创建多维度分面图?

进阶机器学习

答题要点

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# 加载示例数据
tips = sns.load_dataset('tips')

# 1. 基础分面(按列)
g = sns.FacetGrid(tips, col='time', height=4, aspect=1.2)
g.map(sns.histplot, 'total_bill', bins=20)
g.set_titles('{col_name}')
plt.show()

# 2. 行列分面
g = sns.FacetGrid(tips, col='time', row='smoker', height=3, aspect=1.5)
g.map(sns.scatterplot, 'total_bill', 'tip')
g.add_legend()
plt.show()

# 3. 添加hue维度
g = sns.FacetGrid(tips, col='day', hue='sex', height=4, aspect=1.2, palette='Set1')
g.map(sns.scatterplot, 'total_bill', 'tip', alpha=0.6)
g.add_legend()
g.set_axis_labels('Total Bill ($)', 'Tip ($)')
g.set_titles('Day: {col_name}')
plt.show()

# 4. 多种图形类型
g = sns.FacetGrid(tips, col='day', col_wrap=2, height=3)  # col_wrap自动换行
g.map(sns.boxplot, 'time', 'total_bill', order=['Lunch', 'Dinner'])
plt.show()

# 5. 自定义函数
def plot_with_mean(x, y, **kwargs):
    """自定义绘图函数"""
    plt.scatter(x, y, **kwargs)
    plt.axhline(y.mean(), color='red', linestyle='--', label=f'Mean={y.mean():.2f}')
    plt.legend()

g = sns.FacetGrid(tips, col='day', height=4)
g.map(plot_with_mean, 'total_bill', 'tip', alpha=0.5)
plt.show()

# 6. 共享坐标轴
g = sns.FacetGrid(tips, col='day', row='time', sharex=True, sharey=True, height=3)
g.map(sns.scatterplot, 'total_bill', 'tip')
plt.show()

# 7. 设置坐标轴范围
g = sns.FacetGrid(tips, col='day', height=4)
g.map(sns.histplot, 'total_bill', bins=20)
g.set(xlim=(0, 60), ylim=(0, 15))  # 统一设置范围
plt.show()

# 8. 自定义标题和标签
g = sns.FacetGrid(tips, col='day', height=4, aspect=1.2)
g.map(sns.histplot, 'tip', bins=20, color='coral')
g.set_axis_labels('Tip Amount ($)', 'Count')
g.set_titles('Weekday: {col_name}')
g.fig.subplots_adjust(top=0.9)
g.fig.suptitle('Tip Distribution by Day', fontsize=16)
plt.show()

# 9. 分面+回归线
g = sns.lmplot(x='total_bill', y='tip', col='day', row='time', 
               data=tips, height=3, aspect=1.2, ci=None)
plt.show()

# 10. catplot(分类分面)
g = sns.catplot(x='day', y='total_bill', hue='sex', col='time',
                data=tips, kind='box', height=4, aspect=1.2)
plt.show()

# 11. relplot(关系分面)
g = sns.relplot(x='total_bill', y='tip', hue='smoker', col='day',
                data=tips, kind='scatter', height=4, aspect=1.2)
plt.show()

# 12. displot(分布分面)
g = sns.displot(tips, x='total_bill', hue='smoker', col='day',
                kde=True, height=4, aspect=1.2)
plt.show()

# 13. 添加参考线
g = sns.FacetGrid(tips, col='day', height=4)
g.map(sns.scatterplot, 'total_bill', 'tip')
g.map(plt.axline, xy1=(0, 0), slope=0.15, color='red', linestyle='--', label='15% tip')
plt.show()

# 14. 自定义调色板和样式
g = sns.FacetGrid(tips, col='day', hue='time', height=4, aspect=1.2,
                  palette={'Lunch': 'skyblue', 'Dinner': 'coral'},
                  despine=True, margin_titles=True)
g.map(sns.kdeplot, 'total_bill', fill=True, alpha=0.5)
g.add_legend(title='Time')
plt.show()

完整解析在题库里看

核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。

去练这道题

回知识库看这一块

同一能力的其他题