Seaborn:如何为每个 Seaborn 小提琴图应用自定义颜色?

Seaborn: How to apply custom color to each seaborn violinplot?

如何使用自定义颜色来获得像这样的分割小提琴图:image source

标准示例仅显示 2 种颜色,用完 hue 参数。

Seaborn 仅支持拆分小提琴的 2 个色调值。您需要遍历创建的小提琴并更改它们的颜色。

这是一个例子:

from matplotlib import pyplot as plt
from matplotlib.colors import to_rgb
from matplotlib.collections import PolyCollection
import seaborn as sns
import pandas as pd

tips = sns.load_dataset('tips')
ax = sns.violinplot(x="day", y="total_bill", hue="smoker", palette=['.4', '.7'], data=tips, split=True, inner='box')
colors = sns.color_palette('Set2')
for ind, violin in enumerate(ax.findobj(PolyCollection)):
    rgb = to_rgb(colors[ind // 2])
    if ind % 2 != 0:
        rgb = 0.5 + 0.5 * np.array(rgb)  # make whiter
    violin.set_facecolor(rgb)
plt.show()

以下方法添加自定义图例:

from matplotlib import pyplot as plt
from matplotlib.colors import to_rgb
from matplotlib.collections import PolyCollection
from matplotlib.legend_handler import HandlerTuple
import seaborn as sns
import numpy as np

tips = sns.load_dataset('tips')
ax = sns.violinplot(x="day", y="total_bill", hue="smoker", palette=['.2', '.5'], data=tips, split=True, inner='box')
colors = ['dodgerblue', 'crimson', 'gold', 'limegreen']
handles = []
for ind, violin in enumerate(ax.findobj(PolyCollection)):
    rgb = to_rgb(colors[ind // 2])
    if ind % 2 != 0:
        rgb = 0.5 + 0.5 * np.array(rgb)  # make whiter
    violin.set_facecolor(rgb)
    handles.append(plt.Rectangle((0, 0), 0, 0, facecolor=rgb, edgecolor='black'))
ax.legend(handles=[tuple(handles[::2]), tuple(handles[1::2])], labels=tips["smoker"].cat.categories.to_list(),
          title="Smoker", handlelength=4, handler_map={tuple: HandlerTuple(ndivide=None, pad=0)})
plt.show()