- 迭代每个子图/FacetGrid
for ax in g.axes.flat:
.
-
ax.patches
包含matplotlib.patches.Rectangle
and matplotlib.patches.PathPatch
,因此必须使用正确的。
- Caveat: all hues must appear for each group in each Facet, otherwise the
patches
and hatches
will not match.
- 在这种情况下,可能需要手动或条件代码才能正确确定
h
, so zip(patches, h)
works.
- 测试于
python 3.10
, pandas 1.4.2
, matplotlib 3.5.1
, seaborn 0.11.2
import matplotlib as mpl
import seaborn as sns
# load test data
exercise = sns.load_dataset("exercise")
# plot
g = sns.catplot(x="time", y="pulse", hue="kind", data=exercise, col='diet', kind="box")
# hatches must equal the number of hues (3 in this case)
hatches = ['//', '..', 'xx']
# iterate through each subplot / Facet
for ax in g.axes.flat:
# select the correct patches
patches = [patch for patch in ax.patches if type(patch) == mpl.patches.PathPatch]
# the number of patches should be evenly divisible by the number of hatches
h = hatches * (len(patches) // len(hatches))
# iterate through the patches for each subplot
for patch, hatch in zip(patches, h):
patch.set_hatch(hatch)
fc = patch.get_facecolor()
patch.set_edgecolor(fc)
patch.set_facecolor('none')
for lp, hatch in zip(g.legend.get_patches(), hatches):
lp.set_hatch(hatch)
fc = lp.get_facecolor()
lp.set_edgecolor(fc)
lp.set_facecolor('none')
- 如果仅使用轴级别
sns.boxplot
,无需迭代多个轴。
ax = sns.boxplot(x="time", y="pulse", hue="kind", data=exercise)
# select the correct patches
patches = [patch for patch in ax.patches if type(patch) == mpl.patches.PathPatch]
# the number of patches should be evenly divisible by the number of hatches
h = hatches * (len(patches) // len(hatches))
# iterate through the patches for each subplot
for patch, hatch in zip(patches, h):
patch.set_hatch(hatch)
fc = patch.get_facecolor()
patch.set_edgecolor(fc)
patch.set_facecolor('none')
l = ax.legend()
for lp, hatch in zip(l.get_patches(), hatches):
lp.set_hatch(hatch)
fc = lp.get_facecolor()
lp.set_edgecolor(fc)
lp.set_facecolor('none')
- To keep the facecolor of the box plots:
- Remove
patch.set_facecolor('none')
- 将边缘颜色设置为
'k'
(黑色)代替fc
, patch.set_edgecolor('k')
.
ax = sns.boxplot(x="time", y="pulse", hue="kind", data=exercise)
# select the correct patches
patches = [patch for patch in ax.patches if type(patch) == mpl.patches.PathPatch]
# the number of patches should be evenly divisible by the number of hatches
h = hatches * (len(patches) // len(hatches))
# iterate through the patches for each subplot
for patch, hatch in zip(patches, h):
patch.set_hatch(hatch)
patch.set_edgecolor('k')
l = ax.legend()
for lp, hatch in zip(l.get_patches(), hatches):
lp.set_hatch(hatch)
lp.set_edgecolor('k')