Seaborn小提琴图透明度

pr9*_*r94 5 python seaborn violin-plot

我希望在 seaborn.violinplot 中有越来越透明的小提琴。我尝试了以下方法:

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])
Run Code Online (Sandbox Code Playgroud)

Which does not result in the desired output:

在此处输入图片说明

dm2*_*dm2 8

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)
Run Code Online (Sandbox Code Playgroud)

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

Output:

在此处输入图片说明

  • 由于某种原因,虽然这个示例在我在 Tips 数据集上尝试时效果很好,但在应用于我的实际数据时却不起作用。我通过在感兴趣的 PolyCollections 上调用 get_facelor 来解决这个问题,更改 alpha 值,然后应用 set_facecolor; 它神奇地达到了目的。 (2认同)

Mon*_*ave 8

按照同一个线程更新。

更简单的答案是:

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