Tonja Tonja - 3 years ago 200
Python Question

Python: swarm plot covers the median line in box plot

When plotting a swarm plot (seaborn) over a box plot, the points may cover the median line of a box plot.
How can I do the swarm plots dots a bit more transparent so that I also see the median of a box plot?

On the plot we do not see the median line because it is covered by the dot, so, optically I do not know where the median is on the second box. Is it possible to do the poins of the swarm plot more transparent so that I also see the median line?


fig, axes = plt.subplots(nrows=1, ncols=1,figsize=(6,2))
data = pd.DataFrame({'a':[3,3,3,3,4,5,6,8,11,11,8,7,7,7,7,7,7,3,3,3,3,3,7,7,7,7,7,7,7,7,7,7,7,8,9,10,11,12,11,11,11]})
sns.boxplot(x='a',data=data, ax = axes)
ax = sns.swarmplot(x='a', data=data, color = 'grey', ax = axes)

(Making a fig bigger is not an option)

enter image description here

Answer Source

Two options come directly to my mind:

  • Make the swarmplot translucent. This can be done by adding the alpha argument, e.g. alpha=0.5 for half-transparent. Of course the darker the bar in the background, the less visible the points are (hence I made it yellow here).

    import matplotlib.pyplot as plt
    import seaborn as sns
    import pandas as pd
    fig, axes = plt.subplots(figsize=(6,2))
    data = pd.DataFrame({'a':[3,3,3,3,4,5,6,8,11,11,8,7,7,7,7,7,7,3,3,
    sns.boxplot(x='a',data=data, ax = axes, color="gold")
    sns.swarmplot(x='a', data=data, color = 'grey', ax = axes, alpha=0.5)

    enter image description here

  • Show the median line on top of the swarmplot points. This can be done by specifying the zorder of the medianline via a dictionary passed through the medianprops keyword argument.

    sns.boxplot(x='a',data=data, ax = axes, color="gold", medianprops={"zorder":3})

    enter image description here
    In this case, making the median line half-transparent via medianprops={"zorder":3, "alpha":0.6} is equally possible.

Of course any combination of the two options can help as well.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download