首页 > 解决方案 > seaborn 中的一半(不分裂!)小提琴情节

问题描述

目前,seaborn根据一个变量通过设置来提供分割小提琴图的功能。我想制作一个“半”小提琴情节,即每把小提琴的一半被省略的情节。这样的图描绘了类似于每个连续变量的 pdf 的内容,仅绘制在每个分类变量的每条垂直线的一侧。split=Truehue

我已经设法seaborn用绘制的值范围之外的额外数据点和额外的虚拟色调来绘制这个,但我想知道这是否可以在不实际更改数据集的情况下完成,例如在sns.violinplot()参数内。

例如,这张图:

在此处输入图像描述

由此代码段创建:

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

# load dataset from seaborn
datalist = sns.get_dataset_names()
dataset_name = 'iris'
if dataset_name in datalist:
    df = sns.load_dataset(dataset_name)
else:
    print("Dataset with name: " + dataset_name + " was not found in the available datasets online by seaborn.")

# prepare data
df2 = df.append([-999,-999,-999,-999,'setosa'])
df2['huecol'] = 0.0
df2['huecol'].iloc[-1]= -999

# plot
fig = plt.figure(figsize=(6,6))
sns.violinplot(x='species',y="sepal_width",
            split=True, hue ='huecol', inner = 'quartile',
            palette="pastel", data=df2, legend=False)
plt.title('iris')

# remove hue legend
leg = plt.gca().legend()
leg.remove()
plt.ylim([1,5.0])
plt.show()

标签: pythonpython-3.xpandasseaborn

解决方案


答案很简单,不,如果不诱使 seaborn 认为有hue礼物,这是不可能的。

这个答案显示了如何在 matplotlib 中执行此操作,原则上同样可以应用于 seaborn violinplots,即切掉一半的小提琴路径。


推荐阅读