在Seaborn Boxplot上更改框和点分组色相

时间:2018-08-15 17:35:35

标签: python matplotlib seaborn

根据文档,创建一个sns箱线图:

import seaborn as sns
sns.set(style="whitegrid")
tips = sns.load_dataset("tips")
ax = sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips, palette="Set3")

产生一个不错的情节:

enter image description here

但是,我希望能够控制每个组的颜色。我想将吸烟者“是”组显示为灰色框和灰色离群点,而我希望吸烟者“不”组显示为绿色框和绿色离群点。如何编辑基础matplotlib的斧头对象以更改这些属性?

1 个答案:

答案 0 :(得分:1)

最好通过将自己的palette传递给boxplot()来改变盒子的颜色。为了按组更改离群值(“离群”)的颜色,this answer包含了一个解决方案。这是结果代码:

import seaborn as sns, matplotlib.pyplot as plt
sns.set(style="whitegrid")
tips = sns.load_dataset("tips")
ax = sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips,
  palette=sns.color_palette(('.5', 'g')))

# each box in Seaborn boxplot is artist and has 6 associated Line2D objects
for i, box in enumerate(ax.artists):
  col = box.get_facecolor()
  # last Line2D object for each box is the box's fliers
  plt.setp(ax.lines[i*6+5], mfc=col, mec=col)

plt.show()

结果: box plot with desired colors