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()