# 使用 Seaborn 的小提琴圖

Manav Narula 2024年2月15日

`violinplot()` 函式建立了這樣一個圖，並像核密度圖和箱線圖之間的組合一樣描述了分佈。分析和統計人員大量使用它來了解分類資料的分佈。與傳統箱線圖相比，它的主要優勢在於它們也可用於具有多個峰值的分佈。

``````import random
import numpy as np

n = random.sample(range(0, 50), 30)
arr = np.array(n)
sns.violinplot(n)
``````

``````import random
import numpy as np

n = random.sample(range(0, 50), 30)
arr = np.array(n)
sns.violinplot(n)
sns.stripplot(n, color="red")
``````

`violinplot()` 主要用於資料集，顯示具有多個類別的資料分佈。在下面的程式碼中，我們將實現這一點。

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

df = pd.DataFrame(
{
"Quantity": [5, 6, 7, 8, 5, 6, 7, 8, 5, 6, 7, 8, 5, 6, 7, 8],
"Price": [9, 10, 15, 16, 13, 14, 15, 18, 11, 12, 14, 15, 16, 17, 18, 19],
"Day": [1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2],
"Product": [
"A",
"A",
"A",
"A",
"B",
"B",
"B",
"B",
"A",
"A",
"A",
"A",
"B",
"B",
"B",
"B",
],
}
)

sns.violinplot(data=df, y="Price", x="Quantity", hue="Product")
``````

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

df = pd.DataFrame(
{
"Quantity": [5, 6, 7, 8, 5, 6, 7, 8, 5, 6, 7, 8, 5, 6, 7, 8],
"Price": [9, 10, 15, 16, 13, 14, 15, 18, 11, 12, 14, 15, 16, 17, 18, 19],
"Day": [1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2],
"Product": [
"A",
"A",
"A",
"A",
"B",
"B",
"B",
"B",
"A",
"A",
"A",
"A",
"B",
"B",
"B",
"B",
],
}
)

sns.violinplot(
data=df, y="Price", x="Quantity", hue="Product", inner="stick", split=True
)
``````

`violinplot()` 函式返回一個 matplotlib 軸型別物件，以使用所有此類 matplotlib 函式來自定義最終圖形。如果我們想返回一個 `FacetGrid` 型別的物件，我們可以使用 `catplot()` 函式並將 `kind` 引數指定為 `violin`

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.