Home > OS >  Seaborn: How to apply custom color to each seaborn violinplot?
Seaborn: How to apply custom color to each seaborn violinplot?

Time:12-23

How to use custom colors to obtain split violin plots like this: enter image description here

the standard examples only show 2 colors using up the hue parameter.

enter image description here

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()

split violin plots with separate colors

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()

legend for split sns.violinplot

  • Related