HOWTO · Seaborn

Seaborn 繪圖中的字型大小

本教程演示瞭如何在 seaborn 圖中更改字型大小。

本頁內容

在本教程中,我們將討論如何更改 seaborn 圖中的字型大小。

使用 seaborn.set() 函式在 Seaborn 繪圖中設定字型大小

我們可以使用 seaborn.set() 函式來更改 Seaborn 繪圖的配置和主題。要設定字型大小,我們在此函式中使用 font_scale 引數。此引數會自動更改圖形中所有內容的字型,從圖例到軸標籤以及所有內容。

請參考下面的程式碼以瞭解其用法。

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

df = pd.DataFrame(
    {"Day 1": [7, 1, 5, 6, 3, 10, 5, 8], "Day 2": [1, 2, 8, 4, 3, 9, 5, 2]}
)

sns.set(font_scale=2)
p = sns.lineplot(data=df)
p.set_xlabel("X-Axis")
p.set_ylabel("Y-Axis")
p.set_title("Plot")
plt.legend(labels=["Legend_Day1", "Legend_Day2"])

seaborn 字型大小 1

如果函式中未指定任何內容,則它將所有內容設定為預設值。注意使用不同的函式新增不同的元素,以及 set() 函式如何立即更改所有內容的大小。

使用 fontsize 引數更改 Seaborn 圖中的字型大小

有時,我們使用不同的功能在圖中包含不同的元素。我們可以通過將 fontsize 引數設定為其所需的值來改變諸如軸的標籤、圖例和標題等元素的大小。

以下程式碼將對此進行解釋。

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

df = pd.DataFrame(
    {"Day 1": [7, 1, 5, 6, 3, 10, 5, 8], "Day 2": [1, 2, 8, 4, 3, 9, 5, 2]}
)

sns.set()
p = sns.lineplot(data=df)
p.set_xlabel("X-Axis", fontsize=20)
p.set_ylabel("Y-Axis", fontsize=20)
p.set_title("Plot", fontsize=20)
plt.legend(labels=["Legend_Day1", "Legend_Day2"], fontsize=20)

seaborn 字型大小 2

如先前方法中所討論的,在繪圖之前使用 sns.set() 函式將所有內容設定為預設值。