Seaborn violinplot transparency

Viewed 4635

I would like to have increasingly transparent violins in a seaborn.violinplot. I tried the following:

import seaborn as sns

tips = sns.load_dataset("tips")

ax = sns.violinplot(x="day", y="total_bill", data=tips, color='r', alpha=[0.8, 0.6, 0.4, 0.2])

Which does not result in the desired output:

enter image description here

2 Answers

Found this thread looking to change alpha values in general for violin plots, it seems you need to access matplotlib.PolyColections from your ax to even be able to set the alpha values, but since you need to access them anyways, you might as well set alpha values individually (at least in your case since you want individual alpha values).

From my understanding, ax.collections contain both matplotlib.PolyCollections and matplotlib.PathCollections, you only need the PolyCollections, so I did the following and it seems to work:

ax = sns.violinplot(x = 'day', y = 'total_bill', data = tips, color = 'r')
for violin, alpha in zip(ax.collections[::2], [0.8,0.6,0.4,0.2]):
    violin.set_alpha(alpha)

ax.collections[::2] ignores PathCollections, as ax.collections comes in format of [PolyCollection1, PathCollection1, PolyCollection2, PathCollection2, ...]

Output:

enter image description here

Update according to the same thread.

Simpler answer would be:

plt.setp(ax.collections, alpha=.3)

Related