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:
To set a transparent background you could use the RGBA tuple (0,0,0,0) , where the last 0 represents an opacity of 0 .
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.
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).
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:
Update according to the same thread.
Simpler answer would be:
plt.setp(ax.collections, alpha=.3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With