如何使用自定義顏色獲得這樣的分割小提琴圖:
標準示例僅顯示用完hue引數的2 種顏色。

uj5u.com熱心網友回復:
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()

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/390057.html
標籤:Python matplotlib 颜色 海生 小提琴情节
