# 使用 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.