seaborn 中的分面图
seaborn 中的一些绘图函数(如 histplot() 和 lmplot())自带分面功能。您只需传入 col 和/或 row 参数,就能在图中创建分面。
对于不带内置分面的函数,您可以使用 FacetGrid() 手动创建分面,然后通过指定 col 和/或 row 来生成分面。要手动创建分面图,可以使用以下代码:
import seaborn as sns
import matplotlib.pyplot as plt
# 创建分面
facet = sns.FacetGrid(df, col='column_a', row='column_b')
# 生成带分面的散点图
facet.map(plt.scatter, 'column_x', 'column_y')
plt.show()
您还可以通过 hue 参数为点着色,以按某个变量添加另一层数据。
本练习是课程的一部分
面向 R 用户的 Python
交互式实操练习
通过完成这段示例代码来试试这个练习。
import seaborn as sns
import matplotlib.pyplot as plt
# Scatter plot of total_bill and tip faceted by smoker and colored by sex
sns.lmplot(x=____, y=____, data=tips, hue=____, col=____)
plt.show()