Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seaborn stripplot with violin plot bars in front of points

I would like to draw a violin plot behind a jitter stripplot. The resulting plot has the mean/std bar behind the jitter points which makes it hard to see. I'm wondeing if there's a way to bring the bar in front of the points.

import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips")

sns.violinplot(x="day", y="total_bill", data=tips, color="0.8")
sns.stripplot(x="day", y="total_bill", data=tips, jitter=True)
plt.show()

violin

like image 579
Carlos G. Oliver Avatar asked Oct 17 '25 16:10

Carlos G. Oliver


2 Answers

Seaborn doesn't care about exposing the objects it creates to the user. So one would need to collect them from the axes to manipulate them. The property you want to change here is the zorder. So the idea can be to

  1. Plot the violins
  2. Collect the lines and dots from the axes, and give the lines a high zorder, and give the dots an even higher zorder.
  3. Last plot the strip- or swarmplot. This will have a lower zorder automatically.

Example:

import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.collections import PathCollection

tips = sns.load_dataset("tips")

ax = sns.violinplot(x="day", y="total_bill", data=tips, color=".8")

for artist in ax.lines:
    artist.set_zorder(10)
for artist in ax.findobj(PathCollection):
    artist.set_zorder(11)

sns.stripplot(x="day", y="total_bill", data=tips, jitter=True, ax=ax)

plt.show()

enter image description here

like image 54
ImportanceOfBeingErnest Avatar answered Oct 19 '25 06:10

ImportanceOfBeingErnest


I just came across the same problem and could fix it simply by adjusting the zorderparameter in sns.stripplot:

import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips")

sns.violinplot(x="day", y="total_bill", data=tips, color="0.8")
sns.stripplot(x="day", y="total_bill", data=tips, jitter=True, zorder=1)
plt.show()

The result then similar to the answer of @ImportanceOfBeingErnest: enter image description here

like image 40
Felix Reichel Avatar answered Oct 19 '25 05:10

Felix Reichel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!