简体   繁体   English

更改 Seaborn Boxplot 上的 Box 和 Point Grouping Hue

[英]Change Box and Point Grouping Hue on Seaborn Boxplot

Lets create an sns boxplot, per the documentation:让我们根据文档创建一个 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")

Produces a nice plot:产生一个很好的情节:

在此处输入图片说明

However, I want to be able to control each groups' colors.但是,我希望能够控制每个组的颜色。 I would like show smoker "yes" group as gray boxes and grey outlier points, and I would like smoker "no" groups to appear with green boxes and green outlier points.我希望将吸烟者“是”组显示为灰色框和灰色异常值点,并且我希望吸烟者“否”组显示为带有绿色框和绿色异常值点。 How can I edit the underlying matplotlib ax object to change these attributes?如何编辑底层matplotlib ax 对象以更改这些属性?

Changing the colors of the boxes seems best done by passing your own palette to boxplot() .通过将您自己的palette传递给boxplot()似乎最好改变盒子的颜色。 For changing the colors of the outliers ("fliers") by group, this answer included a solution.为了按组更改异常值(“传单”)的颜色,此答案包括一个解决方案。 Here the resulting code:这里得到的代码:

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

And the result:结果: 具有所需颜色的箱线图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM