|
7 | 7 | bars with labels. |
8 | 8 | """ |
9 | 9 |
|
| 10 | +# data from https://allisonhorst.github.io/palmerpenguins/ |
| 11 | + |
10 | 12 | import matplotlib.pyplot as plt |
11 | 13 | import numpy as np |
12 | 14 |
|
| 15 | +species = ("Adelie", "Chinstrap", "Gentoo") |
| 16 | +penguin_means = { |
| 17 | + 'Bill Depth': (18.35, 18.43, 14.98), |
| 18 | + 'Bill Length': (38.79, 48.83, 47.50), |
| 19 | + 'Flipper Length': (189.95, 195.82, 217.19), |
| 20 | +} |
13 | 21 |
|
14 | | -labels = ['G1', 'G2', 'G3', 'G4', 'G5'] |
15 | | -tea_means = [20, 34, 31, 35, 27] |
16 | | -coffee_means = [25, 32, 34, 20, 25] |
17 | | - |
18 | | -x = np.arange(len(labels)) # the label locations |
| 22 | +x = np.arange(len(species)) # the label locations |
19 | 23 | width = 0.25 # the width of the bars |
| 24 | +multiplier = 0 |
20 | 25 |
|
21 | | -fig, ax = plt.subplots() |
22 | | -rects1 = ax.bar(x - width/2, tea_means, width, label='Tea') |
23 | | -rects2 = ax.bar(x + width/2, coffee_means, width, label='Coffee') |
| 26 | +fig, ax = plt.subplots(constrained_layout=True) |
24 | 27 |
|
25 | | -# Add some text for labels, title and custom x-axis tick labels, etc. |
26 | | -ax.set_ylabel('Scores') |
27 | | -ax.set_title('Scores by group and beverage preferences') |
28 | | -ax.set_xticks(x, labels) |
29 | | -ax.legend() |
| 28 | +for attribute, measurement in penguin_means.items(): |
| 29 | + offset = width * multiplier |
| 30 | + rects = ax.bar(x + offset, measurement, width, label=attribute) |
| 31 | + ax.bar_label(rects, padding=3) |
| 32 | + multiplier += 1 |
30 | 33 |
|
31 | | -ax.bar_label(rects1, padding=3) |
32 | | -ax.bar_label(rects2, padding=3) |
33 | | - |
34 | | -fig.tight_layout() |
| 34 | +# Add some text for labels, title and custom x-axis tick labels, etc. |
| 35 | +ax.set_ylabel('Length (mm)') |
| 36 | +ax.set_title('Penguin attributes by species') |
| 37 | +ax.set_xticks(x + width, species) |
| 38 | +ax.legend(loc='upper left', ncols=3) |
| 39 | +ax.set_ylim(0, 250) |
35 | 40 |
|
36 | 41 | plt.show() |
37 | 42 |
|
|
0 commit comments