Seaborn中分组箱图的单独颜色

时间:2018-08-17 16:20:49

标签: python-3.x seaborn

我想调整此箱型图的配色方案,以使左侧的组为深蓝色和浅蓝色,右侧的组为深红色和浅红色。我已经在my_colours中设置了所需的颜色,但仍然不知道该怎么做。这是数据的代码:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

a1 = list(np.random.normal(.70, .20, 20))
a2 = list(np.random.normal(.5, .15, 20))
b1 = list(np.random.normal(.78, .20, 20))
b2 = list(np.random.normal(.4, .25, 20))



levsA = ['a' for i in range(40)]
levsB = ['b' for i in range(40)]

itemsa = [1 for i in range(20)] + [2 for i in range(20)]
itemsb = [1 for i in range(20)] + [2 for i in range(20)]



df = pd.DataFrame({'cs':a1 + a2 + b1+ b2,
                   'levels':levsA + levsB,
                   'type':itemsa + itemsb})


my_colours = ((0.1216, 0.4667, 0.7059),
              (0.8392, 0.1529, 0.1569),
              (0.6824, 0.7804, 0.9098),
              (1, 0.5961, 0.5882))
sns.set_palette(my_colours)


sns.boxplot(x='type', y='cs', hue='levels', data=df)

enter image description here

我想要他们按这个顺序:

enter image description here

1 个答案:

答案 0 :(得分:1)

这些框是PathPatch个。您可以遍历它们并设置其颜色。但是,人们需要注意它们在轴中出现的顺序。

import matplotlib.patches
boxes = ax.findobj(matplotlib.patches.PathPatch)
for color, box in zip(my_colours[::2]+my_colours[1::2], boxes):
    box.set_facecolor(color)

enter image description here