How to use custom colors to obtain split violin plots like this:
the standard examples only show 2 colors using up the hue
parameter.
CodePudding user response:
Seaborn only supports 2 hue values for split violins. You'll need to loop through the created violins and change their color.
Here is an example:
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()
The following approach adds a custom legend:
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()