Seaborn violinplot transparency
Asked Answered
D

2

16

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

Dilapidation answered 26/6, 2020 at 15:26 Comment(0)
B
19

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

Bazooka answered 26/6, 2020 at 15:45 Comment(1)
For some reason, while this example works perfectly when I try it on the tips dataset, it did not work when applied to my actual data. I worked around that by calling get_facelor on the PolyCollections of interest, changing the alpha value, then applying set_facecolor; it mysteriously did the trick.Ligroin
G
8

Update according to the same thread.

Simpler answer would be:

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

Gentility answered 8/8, 2021 at 8:49 Comment(3)
How to update the legend color accordingly?Maury
import matplotlib.patches as mpatches patch = mpatches.Patch(color=(1, 0, 0, 0.3)) ax.legend([patch, ['group1'])Gentility
I was able to do it with: for h in ax.legend_.legendHandles: h.set_alpha(0.3)Maury

© 2022 - 2024 — McMap. All rights reserved.