Search code examples
pythonmatplotlibseabornz-order

Using Seaborn, how do I get all the elements from a pointplot to appear above the elements of a violoinplot?


Using Seaborn 0.6.0, I am trying to overlay a pointplot on a violinplot. My problem is that the 'sticks' from the individual observations of the violinplot are plotted on top of the markers from pointplot as you can see below.

import seaborn as sns
import matplotlib.pyplot as plt

fig, ax = plt.subplots(1, figsize=[12,8])
sns.violinplot(x="day", y="total_bill", hue="smoker", data=tips,
               split=True, inner='stick', ax=ax, palette=['white']*2)
sns.pointplot(x="day", y='total_bill', hue="smoker",
                   data=tips, dodge=0.3, ax=ax, join=False)

enter image description here

Looking closely at this figure, it appears as the green errorbar is plotted above the violoin sticks (look at Saturday), but the blue error bars, and the blue and green dots are plotted underneath the violin sticks.

I have tried passing different combinations of zorder to both functions, but that did not ameliorate the plot appearance. Is there anything I can do to get all the elements from the pointplot to appear above all the elements of the violoinplot?


Solution

  • Similar to Diziet Asahi's answer, but a little bit more straightforward. Since we're setting the zorder, we don't need to draw the plots in the order we want them to appear, which saves the trouble of sorting the artists. I'm also making it so that the pointplot doesn't appear in the legend, where it is not useful.

    import seaborn as sns
    import matploltlib.pyplot as plt
    
    tips = sns.load_dataset("tips")
    
    ax = sns.pointplot(x="day", y='total_bill', hue="smoker",
                  data=tips, dodge=0.3, join=False, palette=['white'])
    plt.setp(ax.lines, zorder=100)
    plt.setp(ax.collections, zorder=100, label="")
    
    sns.violinplot(x="day", y="total_bill", hue="smoker", data=tips,
                   split=True, inner='stick', ax=ax)
    

    enter image description here