Skip to content

Violinplot shows groups swapped contrary to boxplot #3922

Description

@rita-o

Hello,

I am seeing different behavior in seaborn.violinplot compared with seaborn.boxplot when using the same dataframe.

Image

In my case, boxplot looks correct, but violinplot lookes swapped. I found a workaround, but I do not understand the underlying issue: the violin plot only matches the data after I explicitly change the column's type I use for groupping to str instead of the original type which was category. I included an example below.

I am using pandas 3.0.0 and seaborn 0.13.2.

I also saw issue #3893, which seems possibly related.

Thank you in advance,
Rita

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

data_pat = df_long[df_long["Pattern"] == 'MD']
data_pat = data_pat[data_pat["ROI"].isin(["Isocortex", "Cerebellum"])]
data_pat = (
    data_pat
    .groupby(["Subject", "ROI", "Group", "Pattern"], as_index=False)
    .agg({"Value": "mean"})
)

# ----------  !! Violinplot looks wrong unless group is cast to str !! ----------
# data_pat["Group"] = data_pat["Group"].astype(str)

hue_order = ['WT', 'HTZ']

fig, axes = plt.subplots(1, 2, figsize=(10,4), sharey=True)

# ---------- LEFT: Violin ----------
ax = axes[0]
sns.violinplot(
    data=data_pat,
    x="ROI",
    y="Value",
    hue="Group",
    width=0.6,
    linewidth=0.3,
    gap=0.25,
    linecolor='grey',
    saturation=0.9,
    hue_order=hue_order,
    ax=ax,
)
sns.stripplot(
    data=data_pat,
    x="ROI",
    y="Value",
    hue="Group",
    hue_order=hue_order,
    dodge=True,
    jitter=False,
    size=3.5,
    alpha=0.5,
    palette=["#bfbfbf"] * 2,
    ax=ax,
)
ax.set_title("Violinplot")
  
# ---------- RIGHT: Boxplot -----------
ax = axes[1]

sns.boxplot(
    data=data_pat,
    x="ROI",
    y="Value",
    hue="Group",
    width=0.6,
    fliersize=0,
    linewidth=0.3,
    gap=0.25,
    linecolor='grey',
    saturation=0.9,
    hue_order=hue_order,
    ax=ax,
)
sns.stripplot(
    data=data_pat,
    x="ROI",
    y="Value",
    hue="Group",
    hue_order=hue_order,
    dodge=True,
    jitter=False,
    size=3.5,
    alpha=0.5,
    palette=["#bfbfbf"] * 2,
    ax=ax,
)
ax.set_title("Boxplot")

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions