Seaborn中的半小提琴图(非分裂)。

22

目前seaborn提供了分组小提琴图的功能,只需通过设置split=Truehue变量即可。我想制作一个“半”小提琴图,即省略每个小提琴的一半。这样的图表类似于每个分类变量垂直线的一侧上绘制的每个连续变量的概率密度函数(pdf)。

我已经成功地用一个超出值范围和一个虚拟hue来欺骗seaborn绘制此图,但我想知道是否可以在不实际更改数据集的情况下完成此操作,例如在sns.violinplot()参数内。

例如,此图:

enter image description here

是通过以下代码段创建的:

# 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()

3
使用matplotlib代替seaborn,但这个链接可能会有所帮助:https://dev59.com/tF0a5IYBdhLWcg3w88k0#29781988/ - PlasmaBinturong
暂时修改数据以生成图表有什么问题? - Nils Werner
1
@jpp 或许可以尝试使用脊形图 https://seaborn.pydata.org/examples/kde_ridgeplot.html - Andrew Fogg
3个回答

10

不需要修改数据:

ax = sns.violinplot(
    data=tips,
    x="day", y="total_bill", hue=True,
    hue_order=[True, False], split=True,
)
ax.legend_ = None

enter image description here


非常感谢这个技巧,我认为应该被接受的答案! :) 很高兴我一直向下滚动 ^^ - nicrie

9
答案很简单,没有使用hue的话,seaborn无法完成此操作。可以在matplotlib中实现此功能,而且原理也可以应用于seaborn violinplots中,即切掉小提琴路径的一半。这个答案展示了如何在matplotlib中完成此操作。

谢谢你提供的链接,但是你能否提供一下使用seaborn实现同样效果的代码呢?谢谢! - Sergey Zakharov
1
更新:实际上它不应该是完全相同的,而只是小提琴的一半。您链接中的图表是双面小提琴,这不是TS所要求的。 - Sergey Zakharov
@SergeyZakharov 这个问题中的代码展示了如何使用seaborn实现。我想我不需要重复它。链接的matplotlib代码分别生成了小提琴图的两侧;如果你只想要一半的小提琴,那么你可以省略答案的其中一个部分。 - ImportanceOfBeingErnest
现在我明白如何做了。谢谢。 - Sergey Zakharov

9

我曾寻找类似的解决方案,但没有找到令人满意的内容。最终,我多次调用seaborn.kdeplot,因为violinplot本质上是一个单侧核密度图。

示例

下面是categorical_kde_plot函数的定义

categorical_kde_plot(
    df,
    variable="tip",
    category="day",
    category_order=["Thur", "Fri", "Sat", "Sun"],
    horizontal=False,
)

horizontal=True 时,输出将如下所示:

代码

import seaborn as sns
from matplotlib import pyplot as plt


def categorical_kde_plot(
    df,
    variable,
    category,
    category_order=None,
    horizontal=False,
    rug=True,
    figsize=None,
):
    """Draw a categorical KDE plot

    Parameters
    ----------
    df: pd.DataFrame
        The data to plot
    variable: str
        The column in the `df` to plot (continuous variable)
    category: str
        The column in the `df` to use for grouping (categorical variable)
    horizontal: bool
        If True, draw density plots horizontally. Otherwise, draw them
        vertically.
    rug: bool
        If True, add also a sns.rugplot.
    figsize: tuple or None
        If None, use default figsize of (7, 1*len(categories))
        If tuple, use that figsize. Given to plt.subplots as an argument.
    """
    if category_order is None:
        categories = list(df[category].unique())
    else:
        categories = category_order[:]

    figsize = (7, 1.0 * len(categories))

    fig, axes = plt.subplots(
        nrows=len(categories) if horizontal else 1,
        ncols=1 if horizontal else len(categories),
        figsize=figsize[::-1] if not horizontal else figsize,
        sharex=horizontal,
        sharey=not horizontal,
    )

    for i, (cat, ax) in enumerate(zip(categories, axes)):
        sns.kdeplot(
            data=df[df[category] == cat],
            x=variable if horizontal else None,
            y=None if horizontal else variable,
            # kde kwargs
            bw_adjust=0.5,
            clip_on=False,
            fill=True,
            alpha=1,
            linewidth=1.5,
            ax=ax,
            color="lightslategray",
        )

        keep_variable_axis = (i == len(fig.axes) - 1) if horizontal else (i == 0)

        if rug:
            sns.rugplot(
                data=df[df[category] == cat],
                x=variable if horizontal else None,
                y=None if horizontal else variable,
                ax=ax,
                color="black",
                height=0.025 if keep_variable_axis else 0.04,
            )

        _format_axis(
            ax,
            cat,
            horizontal,
            keep_variable_axis=keep_variable_axis,
        )

    plt.tight_layout()
    plt.show()


def _format_axis(ax, category, horizontal=False, keep_variable_axis=True):

    # Remove the axis lines
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)

    if horizontal:
        ax.set_ylabel(None)
        lim = ax.get_ylim()
        ax.set_yticks([(lim[0] + lim[1]) / 2])
        ax.set_yticklabels([category])
        if not keep_variable_axis:
            ax.get_xaxis().set_visible(False)
            ax.spines["bottom"].set_visible(False)
    else:
        ax.set_xlabel(None)
        lim = ax.get_xlim()
        ax.set_xticks([(lim[0] + lim[1]) / 2])
        ax.set_xticklabels([category])
        if not keep_variable_axis:
            ax.get_yaxis().set_visible(False)
            ax.spines["left"].set_visible(False)


if __name__ == "__main__":
    df = sns.load_dataset("tips")

    categorical_kde_plot(
        df,
        variable="tip",
        category="day",
        category_order=["Thur", "Fri", "Sat", "Sun"],
        horizontal=True,
    )

这是一个不错的答案,但在这里自己编写for循环明显有些过度了,当使用displot的列分面和y轴上的kde图时,这种方法非常简单。 - mwaskom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接