Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seaborn violinplot transparency

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

like image 498
pr94 Avatar asked Jun 26 '20 15:06

pr94


People also ask

How do I make the plot transparent in Seaborn?

To set a transparent background you could use the RGBA tuple (0,0,0,0) , where the last 0 represents an opacity of 0 .

What is Violinplot in Seaborn?

A violin plot plays a similar role as a box and whisker plot. It shows the distribution of quantitative data across several levels of one (or more) categorical variables such that those distributions can be compared.

Are violin plots better or worse than box plots?

A violin plot is more informative than a plain box plot. While a box plot only shows summary statistics such as mean/median and interquartile ranges, the violin plot shows the full distribution of the data. The difference is particularly useful when the data distribution is multimodal (more than one peak).


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

like image 84
dm2 Avatar answered Oct 15 '22 15:10

dm2


Update according to the same thread.

Simpler answer would be:

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

like image 20
MonsieurWave Avatar answered Oct 15 '22 14:10

MonsieurWave