Seaborn 長條圖

在 Python 中處理類別資料

Kasey Jones

Research Data Scientist

傳統長條圖

# Code provided for clarity
reviews["Traveler type"].value_counts().plot.bar()

依不同旅客類型計算評論數量的長條圖。

在 Python 中處理類別資料

語法

sns.set(font_scale=1.3)
sns.set_style("darkgrid")

sns.catplot(x="Traveler type", y="Score", data=reviews, kind="bar")

依旅客類型呈現飯店評論的 seaborn 分類長條圖。

在 Python 中處理類別資料

調整類別順序

reviews["Traveler type"] = reviews["Traveler type"].astype("category")
reviews["Traveler type"].cat.categories
Index(['Business', 'Couples', 'Families', 'Friends', 'Solo'], dtype='object')
在 Python 中處理類別資料

更新後的視覺化

sns.catplot(x="Traveler type", y="Score", data=reviews, kind="bar")

  • 注意:catplot()order 參數
在 Python 中處理類別資料

hue 參數

  • hue
    • data 中變數名稱
    • 用於依第二個類別分割資料
    • 也用來著色圖形
sns.set(font_scale=1.2)
sns.set_style("darkgrid")
sns.catplot(x="Traveler type", y="Score", data=reviews, kind="bar",
            hue="Tennis court")  # <--- new parameter
在 Python 中處理類別資料

跨兩個變數的長條圖

在 Python 中處理類別資料

長條圖練習

在 Python 中處理類別資料

Preparing Video For Download...