Home > Net >  How to shift quartile lines in seaborn grouped violin plots?
How to shift quartile lines in seaborn grouped violin plots?

Time:12-02

Consider the following seaborn grouped violinplot with split violins, where I inserted a small space inbetween.

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

sns.set_theme(style="whitegrid")

tips = sns.load_dataset("tips")

fig, ax = plt.subplots()
sns.violinplot(
    data=tips, x="day", y="total_bill", hue="smoker", split=True, inner="quart", linewidth=1,
    palette={"Yes": "b", "No": ".85"}, ax=ax
)
sns.despine(left=True)
delta = 0.025
for ii, item in enumerate(ax.collections):
    if isinstance(item, matplotlib.collections.PolyCollection):
        path, = item.get_paths()
        vertices = path.vertices
        if ii % 2:  # -> to right
            vertices[:, 0]  = delta
        else:  # -> to left
            vertices[:, 0] -= delta
plt.show()

How can I shift the quartile (and median) indicating dotted (and dashed) lines back inside the violins?

grouped violinplot with split violins

CodePudding user response:

You can do it exactly the same way as you did with the violins:

for i, line in enumerate(ax.get_lines()):
    line.get_path().vertices[:, 0]  = delta if i // 3 % 2 else -delta

enter image description here

  • Related