.patches
而不是artists
。然而,有不同类型的patches
,所以选择第3个patch并不简单。list(ax.patches)
返回以下列表:PathPatch
对象。因此,对于第3个盒图,正确的patch
是ax.patches[4]
[<matplotlib.patches.Rectangle at 0x1fe73317910>,
<matplotlib.patches.PathPatch at 0x1fe72508050>,
<matplotlib.patches.Rectangle at 0x1fe76b497d0>,
<matplotlib.patches.PathPatch at 0x1fe6c35cc90>,
<matplotlib.patches.PathPatch at 0x1fe76db67d0>,
<matplotlib.patches.PathPatch at 0x1fe6c35c610>,
<matplotlib.patches.PathPatch at 0x1fe715d8d90>,
<matplotlib.patches.PathPatch at 0x1fe6c31b0d0>,
<matplotlib.patches.PathPatch at 0x1fe6c2f5a90>,
<matplotlib.patches.PathPatch at 0x1fe74df6450>]
tips = sns.load_dataset("tips")
ax = sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips, palette="Set3")
# Select which box you want to change
mybox = ax.patches[4]
# Change the appearance of that box
mybox.set_facecolor('red')
mybox.set_edgecolor('black')
mybox.set_linewidth(3)
sns.boxplot
创建的箱子实际上只是matplotlib.patches.PathPatch
对象。这些对象以列表形式存储在ax.artists
中。ax.artists
进行索引来选择特定的箱子。然后,您可以设置facecolor
、edgecolor
和linewidth
等许多其他属性。import seaborn as sns
import 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="Set3")
# Select which box you want to change
mybox = ax.artists[2]
# Change the appearance of that box
mybox.set_facecolor('red')
mybox.set_edgecolor('black')
mybox.set_linewidth(3)
plt.show()
ax.lines
中。通过一些试错,您可以找到对应于您想要更改的平均值的线条,然后执行 ax.lines[X].set_color('blue')
或类似操作(其中 X 是要更改的线条的索引)。 - tmdavisonax.lines[0:5]
对应于第一个箱子,ax.lines[5:11]
对应于第二个箱子,以此类推。ax.lines[0:2]
将更改盒须,ax.lines[2:4]
将更改盖帽,而 ax.lines[4]
将更改第一个箱子的平均线。 - tmdavisonSeaborn使用Matplotlib作为底层库。在Matplotlib 3.5中,盒子被存储在boxes
而不是artists
中。详见此处。
因此,您可以像下面这样设置盒子的颜色:
ax = sns.boxplot(x="day", y="total_bill", hue="smoker",
data=tips, palette="Set3")
# Select which box you want to change
mybox = ax.patches[2] # `patches` instead of `artists`
# Change the appearance of that box
mybox.set_facecolor('red')
mybox.set_edgecolor('black')
mybox.set_linewidth(3)