|
3 | 3 | Box plots with custom fill colors
|
4 | 4 | =================================
|
5 | 5 |
|
6 |
| -This plot illustrates how to create two types of box plots |
7 |
| -(rectangular and notched), and how to fill them with custom |
8 |
| -colors by accessing the properties of the artists of the |
9 |
| -box plots. Additionally, the ``labels`` parameter is used to |
10 |
| -provide x-tick labels for each sample. |
11 |
| -
|
12 |
| -A good general reference on boxplots and their history can be found |
13 |
| -here: http://vita.had.co.nz/papers/boxplots.pdf |
| 6 | +To color each box of a box plot individually: |
| 7 | +
|
| 8 | +1) use the keyword argument ``patch_artist=True`` to create filled boxes. |
| 9 | +2) loop through the created boxes and adapt their color. |
14 | 10 | """
|
15 | 11 |
|
16 | 12 | import matplotlib.pyplot as plt
|
17 | 13 | import numpy as np
|
18 | 14 |
|
19 |
| -# Random test data |
20 | 15 | np.random.seed(19680801)
|
21 |
| -all_data = [np.random.normal(0, std, size=100) for std in range(1, 4)] |
22 |
| -labels = ['x1', 'x2', 'x3'] |
23 |
| - |
24 |
| -fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(9, 4)) |
25 |
| - |
26 |
| -# rectangular box plot |
27 |
| -bplot1 = ax1.boxplot(all_data, |
28 |
| - vert=True, # vertical box alignment |
29 |
| - patch_artist=True, # fill with color |
30 |
| - labels=labels) # will be used to label x-ticks |
31 |
| -ax1.set_title('Rectangular box plot') |
32 |
| - |
33 |
| -# notch shape box plot |
34 |
| -bplot2 = ax2.boxplot(all_data, |
35 |
| - notch=True, # notch shape |
36 |
| - vert=True, # vertical box alignment |
37 |
| - patch_artist=True, # fill with color |
38 |
| - labels=labels) # will be used to label x-ticks |
39 |
| -ax2.set_title('Notched box plot') |
| 16 | +fruit_weights = [ |
| 17 | + np.random.normal(130, 10, size=100), |
| 18 | + np.random.normal(125, 20, size=100), |
| 19 | + np.random.normal(120, 30, size=100), |
| 20 | +] |
| 21 | +labels = ['peaches', 'oranges', 'tomatoes'] |
| 22 | +colors = ['peachpuff', 'orange', 'tomato'] |
| 23 | + |
| 24 | +fig, ax = plt.subplots() |
| 25 | +ax.set_ylabel('fruit weight (g)') |
| 26 | + |
| 27 | +bplot = ax.boxplot(fruit_weights, |
| 28 | + patch_artist=True, # fill with color |
| 29 | + labels=labels) # will be used to label x-ticks |
40 | 30 |
|
41 | 31 | # fill with colors
|
42 |
| -colors = ['pink', 'lightblue', 'lightgreen'] |
43 |
| -for bplot in (bplot1, bplot2): |
44 |
| - for patch, color in zip(bplot['boxes'], colors): |
45 |
| - patch.set_facecolor(color) |
46 |
| - |
47 |
| -# adding horizontal grid lines |
48 |
| -for ax in [ax1, ax2]: |
49 |
| - ax.yaxis.grid(True) |
50 |
| - ax.set_xlabel('Three separate samples') |
51 |
| - ax.set_ylabel('Observed values') |
| 32 | +for patch, color in zip(bplot['boxes'], colors): |
| 33 | + patch.set_facecolor(color) |
52 | 34 |
|
53 | 35 | plt.show()
|
54 | 36 |
|
|
0 commit comments