HOWTO · Seaborn
在 Seaborn 繪圖中新增軸標籤
使用 Axes 方法或 Matplotlib pyplot 在 Seaborn 圖中設定 x 軸和 y 軸標籤,並自訂其外觀。
本頁內容
若要新增或取代 Seaborn 圖表的軸標籤,請在繪圖函式回傳的 Matplotlib Axes 物件上呼叫 set_xlabel() 和 set_ylabel()。Seaborn 通常會根據對應至 x 和 y 的變數產生預設標籤,但實際標籤仍取決於圖表類型及輸入資料。若需要適合讀者理解的名稱,請明確設定標籤。
使用 Axes.set_xlabel() 和 Axes.set_ylabel()
這種方式會直接設定 Seaborn 回傳的特定座標軸,因此圖表包含多個繪圖時也能清楚指定目標。範例使用小型的記憶體內資料集,並在設定標籤後將它們印出。
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import seaborn as sns
days = ["Mon", "Tue", "Wed"]
orders = [12, 18, 15]
ax = sns.lineplot(x=days, y=orders, marker="o")
ax.set_xlabel("Day", fontsize=12)
ax.set_ylabel("Orders", fontsize=12)
print(ax.get_xlabel(), "|", ax.get_ylabel())
plt.close()
fontsize 和 color 是調整標籤外觀時常用的文字屬性;例如,可將 color="navy" 傳給其中一個方法。這些呼叫會變更軸標籤,標題則是另外設定:需要標題時,請使用 ax.set_title("Orders by day")。如果刻度標籤擠在一起,可以使用 ax.tick_params(axis="x", labelrotation=45) 旋轉標籤,或在該座標軸上建立繪圖前,透過 fig, ax = plt.subplots(figsize=(8, 4)) 加大圖表空間。
使用 Axes.set() 設定兩個標籤
若要在同一個 Axes 物件上設定兩個標籤,可以使用 set()。它的 xlabel 和 ylabel 關鍵字引數可一次完成這兩項設定;請將回傳的座標軸存入變數,明確指定設定對象。
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import seaborn as sns
months = ["Jan", "Feb", "Mar"]
visitors = [120, 145, 138]
ax = sns.lineplot(x=months, y=visitors, marker="o")
ax.set(xlabel="Month", ylabel="Visitors")
print(ax.get_xlabel(), "|", ax.get_ylabel())
plt.close()
使用 matplotlib.pyplot.xlabel() 和 matplotlib.pyplot.ylabel() 設定標籤
在只處理一個目前座標軸的簡單指令碼中,matplotlib.pyplot.xlabel() 和 matplotlib.pyplot.ylabel() 函式十分方便。它們會作用於 pyplot 的目前座標軸;因此,若圖表包含多個繪圖,請先選取要設定的座標軸。範例會先將 Seaborn 的座標軸設為目前座標軸,再套用標籤。
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import seaborn as sns
products = ["A", "B", "C"]
sales = [8, 13, 10]
ax = sns.barplot(x=products, y=sales)
plt.sca(ax)
plt.xlabel("Product", fontsize=12)
plt.ylabel("Sales", fontsize=12)
print(ax.get_xlabel(), "|", ax.get_ylabel())
plt.close()
若只有一個繪圖,兩種 API 都能設定標籤;若已有繪圖物件,或需要管理多個座標軸,建議使用 Axes 方法。當程式脈絡適合採用目前座標軸的操作方式時,則可使用 pyplot。若要新增格線,請在指定的座標軸上呼叫 ax.grid(True)。