fabianegli
fabianegli

Reputation: 2246

How to use the `split` argument in a `seaborn.violinplot` in a `seaborn.FacetGrid`

The quest is to make a FacetGrid containing violinplots with split violins.

Setup for a FacetGrid containing violinplots without split:

import numpy as np
import pandas as pd
import seaborn as sns
np.random.seed(42)
df = pd.DataFrame(
    {
        "value": np.random.rand(20),
        "condition": ["true", "false"]*10,
        "category": ["right"]*10 + ["wrong"]*10,
    }
)
g = sns.FacetGrid(data=df, col="category", hue="condition", col_wrap=5)
g.map(sns.violinplot, "value");

A FacetGrid with violinplots.

The following is a violin plot showing part of the data as a violinplot with a "split":

p = sns.violinplot(
    data=df[df["category"]=="right"],
    x="value",
    y="category",
    hue="condition",
    split=True
)

enter image description here

Adding the split argument within the map doesn't produce the desired split plots. It is as if split is being ignored:

g = sns.FacetGrid(data=df, col="category", hue="condition", col_wrap=5)
g.map(sns.violinplot, "value", split=True);

enter image description here

sns.__version__ # '0.12.1'

Upvotes: 1

Views: 622

Answers (1)

JohanC
JohanC

Reputation: 80449

It seems seaborn doesn't allow y to be empty for these catplots. You can work around this by creating a dummy y value:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

np.random.seed(42)
df = pd.DataFrame({"value": np.random.rand(20),
                   "condition": ["true", "false"] * 10,
                   "category": ["right"] * 10 + ["wrong"] * 10})
df["y"] = "" # create a dummy column to be used as "y="
sns.catplot(data=df, x="value", y="y", col="condition", hue="category", kind="violin", split=True)
plt.show()

sns.catplot with dummy y

Upvotes: 3

Related Questions