How would you go about changing the style of only some boxes in a matplotlib boxplot? Below, you can see an example of styling, but I would like the style to only apply to one of the boxes.
Asked
Active
Viewed 277 times
0
-
What do you mean by "One of the boxes in boxplot"? – harvpan May 16 '18 at 21:11
-
@HarvIpan In each subplot, you can see four "boxes" (consisting of a rectangle, fliers, etc.) labeled 1 through 4. I would like to apply a particular style to only one of them (e.g. by making only one box dotted). Does that help? – hyperdo May 16 '18 at 21:18
1 Answers
1
The same question has been asked for seaborn boxplots already. For matplotlib boxplots this is even easier, since the boxplot
directly returns a dictionary of the involved artists, see boxplot
documentation.
This means that if bplot = ax.boxplot(..)
is your boxplot, you may access the boxes via bplot['boxes']
, select one of them and set its linestyle to your desire. E.g.
bplot['boxes'][2].set_linestyle("-.")
Modifying the boxplot_color example
import matplotlib.pyplot as plt
import numpy as np
# Random test data
np.random.seed(19680801)
all_data = [np.random.normal(0, std, size=100) for std in range(1, 4)]
labels = ['x1', 'x2', 'x3']
fig, ax = plt.subplots()
# notch shape box plot
bplot = ax.boxplot(all_data, vert=True, patch_artist=True, labels=labels)
# Loop through boxes and colorize them individually
colors = ['pink', 'lightblue', 'lightgreen']
for patch, color in zip(bplot['boxes'], colors):
patch.set_facecolor(color)
# Make the third box dotted
bplot['boxes'][2].set_linestyle("-.")
plt.show()

ImportanceOfBeingErnest
- 321,279
- 53
- 665
- 712