I would like to superimpose a hatched boxplot on another one. On the right figure, I get almost what I want with the shown code except the caps and median are not the same colors as the "walls" of the boxplot.
If I activate the first exit() (left figure), and then the second (middle figure), I realize matplotlib was not really designed to superimpose boxplots. Would there be a way to get what I want ?
Code excerpted from this answer
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
fig, ax = plt.subplots(figsize=(2, 5))
tips = sns.load_dataset("tips")
tips['total_bill_plus5'] = tips['total_bill'] + 5
sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips, fliersize=0, whis=0)
plt.ylim(0, 50)
#exit()
sns.boxplot(x="day", y="total_bill_plus5", hue="smoker", data=tips, fliersize=0, whis=0)
#exit()
ax.get_legend().remove()
box_patches = [patch for patch in ax.patches if type(patch) == matplotlib.patches.PathPatch]
if len(box_patches) == 0: # in matplotlib older than 3.5, the boxes are stored in ax.artists
box_patches = ax.artists
num_patches = len(box_patches)
lines_per_boxplot = len(ax.lines) // num_patches
col = (.5, .5, .5, 1)
for i, patch in enumerate( box_patches[int(num_patches/2):] ):
patch.set_edgecolor(col)
patch.set_facecolor('None')
# Each box has associated Line2D objects (to make the whiskers, fliers, etc.)
# Loop over them here, and use the same color as above
for line in ax.lines[i * lines_per_boxplot: (i + 1) * lines_per_boxplot]:
line.set_color(col)
line.set_mfc(col) # facecolor of fliers
line.set_mec(col) # edgecolor of fliers
patch.set_hatch('////')
Sorry I don't think it's a duplicate since I see no overlay of boxplots on How to add hatches to boxplots with sns.boxplot or sns.catplot