Seaborn 子圖

Manav Narula 2024年2月15日
  1. 在 Python 中使用 matplotlib.pyplot.subplots 函式繪製 Seaborn 子圖
  2. 在 Python 中使用 matplotlib.pyploy.add_subplot() 函式繪製 Seaborn 子圖
Seaborn 子圖

在本教程中,我們將學習如何在 Python 中繪製 seaborn 子圖。

在 Python 中使用 matplotlib.pyplot.subplots 函式繪製 Seaborn 子圖

我們知道大多數 seaborn 圖返回一個 matplotlib 軸物件。所以我們可以使用 subplots() 函式來繪製子圖。

首先,我們將使用此函式建立所需的圖形併為整個子圖建立網格。然後我們將繼續繪製必要的圖形。

下面的程式碼將解釋這一點。

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

fig, axes = plt.subplots(1, 2)

seaborn 子圖

使用上面擷取的程式碼,我們能夠將最終圖形劃分為 1x2 子圖。返回的軸物件是指定大小的 numpy 陣列,在我們的示例中為 1x2。我們將在繪製子圖時使用這個物件。我們將使用 seaborn 繪圖函式中的 ax 引數指定子圖所需的位置。

請參考下面的程式碼片段。

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


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


fig, axes = plt.subplots(1, 2)

sns.lineplot(x="Day", y="Price 1", data=df, ax=axes[0])
sns.lineplot(x="Day", y="Price 2", data=df, ax=axes[1])
axes[0].set_title("First")
axes[1].set_title("Second")
plt.suptitle("Main")

seaborn 子圖

我們可以使用軸物件為單個繪圖新增自定義,例如新增標題和所有內容。請注意,我們使用 suptitle() 函式為主圖新增標題。

在 Python 中使用 matplotlib.pyploy.add_subplot() 函式繪製 Seaborn 子圖

與之前的方法不同,此函式可用於動態建立子圖。在我們的示例中,我們將使用 for 迴圈建立帶有子圖的 axes 物件。

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

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

fig = plt.figure()

for i in range(1, 3):
    axes = fig.add_subplot(1, 2, i)
    if i == 1:
        sns.lineplot(x="Day", y="Price 1", data=df)
    else:
        sns.lineplot(x="Day", y="Price 2", data=df)

seaborn 子圖

我們為我們的圖建立了一個 1x2 的子圖。i 引數用於單獨訪問圖。我們也會在繪圖時使用它。我們可以使用 subplots_adjust() 函式來調整最終圖形中的間距和所有內容。

作者: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn