Seaborn 多線圖

Ammar Ali 2024年2月15日
Seaborn 多線圖

本教程將討論使用 Seaborn 的 lineplot() 函式建立多線圖。

Seaborn 中的多線圖

Seaborn 的 lineplot() 函式將資料繪製為一條線。我們必須將 x 和 y 軸值傳遞給函式來繪製一條線。如果我們想繪製多條線,我們必須為給定資料製作一個資料框,其中每列對應於每條線。

要在同一個圖上繪製五條線,我們必須將資料框中每條線的資料儲存為一列,然後將資料框傳遞給 lineplot() 以繪製多條線。lineplot() 函式將使用資料框的列值作為 y 軸值,並將值的索引作為 x 軸值來繪製線條。

讓我們建立一個包含五列六行的陣列。我們將使用 pandas 庫的 DataFrame() 函式來建立資料框。我們必須在 DataFrame() 函式中傳遞陣列以及行數和列數。

我們將使用 lineplot() 函式的資料引數在函式內部傳遞資料框。請參閱下面的程式碼。

import seaborn as snNew
import pandas as pdNew
import matplotlib.pyplot as pltNew

array = [
    [11, 1, 0, 2, 0],
    [3, 8, 0, 1, 0],
    [0, 16, 3, 0, 0],
    [0, 0, 12, 0, 0],
    [0, 0, 0, 13, 0],
    [0, 1, 0, 0, 16],
]

DetaFrame_cm = pdNew.DataFrame(array, range(6), range(5))
snNew.lineplot(data=DetaFrame_cm)
pltNew.show()

多線圖 Seaborn

該函式繪製了五條具有不同顏色和線型的線。我們可以使用 NumPy 庫的 ndarray() 函式建立給定資料的 NumPy 陣列來繪製五條線,並可以使用它來繪製五條線。

使用 lineplot() 函式的標記引數線上條內繪製標記。預設情況下,此引數為 false,但我們可以將其設定為 true 或包含標記符號的列表。如果引數設定為 true,該函式將處理標記。

我們可以使用 palette 引數更改調色盤以賦予線條顏色,並將其值設定為調色盤名稱,例如深色用於深色。預設情況下,圖例設定為 true,但我們可以通過將 legend 引數設定為 false 來隱藏圖例。

使用 linewidth 引數,我們可以更改線寬並將其值設定為浮點數。我們可以使用 msmarkersize 引數將標記大小設定為任何浮點值。

使用 mfcmarkerfacecolor 引數和顏色或第一個字母(如 r 表示紅色)將標記面顏色設定為任何顏色。我們可以使用 mecmarkeredgecolor 引數將標記邊緣顏色設定為任何顏色。

使用 mewmarkeredgewidth 引數將標記邊緣寬度設定為任何浮點值。讓我們更改上面提到的屬性。

請參閱下面的程式碼。

import seaborn as snNew
import pandas as pdNew
import matplotlib.pyplot as pltNew

array = [
    [11, 1, 0, 2, 0],
    [3, 8, 0, 1, 0],
    [0, 16, 3, 0, 0],
    [0, 0, 12, 0, 0],
    [0, 0, 0, 13, 0],
    [0, 1, 0, 0, 16],
]

DetaFrame_cm = pdNew.DataFrame(array, range(6), range(5))
snNew.lineplot(
    data=DetaFrame_cm,
    markers=["o", "d", "h", "p", "*"],
    palette="dark",
    legend=False,
    linewidth=2,
    ms=15,
    mec="r",
    mew=2,
    mfc="g",
)
pltNew.show()

輸出:

改變多線圖的屬性

使用 set() 函式和 font_scale 引數在繪圖中設定文字的字型大小。要增加字型大小,我們必須將 font_scale 值設定為大於 1,減小其值,然後將其設定為小於 1。

為了增加圖中文字的字型大小,我們必須使用下面的程式碼。

snNew.set(font_scale=1.5)
作者: Ammar Ali
Ammar Ali avatar Ammar Ali avatar

Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.

LinkedIn Facebook

相關文章 - Seaborn Plot