更改Seaborn Boxp上的方框和点分组色调

2024-05-15 21:01:04 发布

您现在位置:Python中文网/ 问答频道 /正文

让我们根据文档创建一个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

但是,我希望能够控制每个组的颜色。我想显示吸烟者“是”组为灰色框和灰色离群点,我想吸烟者“否”组出现绿色框和绿色离群点。如何编辑底层matplotlibax对象以更改这些属性?在


Tags: 文档importstyleasloadseabornset绿色
1条回答
网友
1楼 · 发布于 2024-05-15 21:01:04

更改方框的颜色最好是将您自己的palette传递给boxplot()。对于按组更改离群值(“fliers”)的颜色,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

相关问题 更多 >