|
19 | 19 | fig.subplots_adjust(wspace=0)
|
20 | 20 |
|
21 | 21 | # pie chart parameters
|
22 |
| -ratios = [.27, .56, .17] |
| 22 | +overall_ratios = [.27, .56, .17] |
23 | 23 | labels = ['Approve', 'Disapprove', 'Undecided']
|
24 | 24 | explode = [0.1, 0, 0]
|
25 | 25 | # rotate so that first wedge is split by the x-axis
|
26 |
| -angle = -180 * ratios[0] |
27 |
| -ax1.pie(ratios, autopct='%1.1f%%', startangle=angle, |
28 |
| - labels=labels, explode=explode) |
| 26 | +angle = -180 * overall_ratios[0] |
| 27 | +wedges, *_ = ax1.pie(overall_ratios, autopct='%1.1f%%', startangle=angle, |
| 28 | + labels=labels, explode=explode) |
29 | 29 |
|
30 | 30 | # bar chart parameters
|
31 |
| - |
32 |
| -xpos = 0 |
33 |
| -bottom = 0 |
34 |
| -ratios = [.33, .54, .07, .06] |
| 31 | +age_ratios = [.33, .54, .07, .06] |
| 32 | +age_labels = ['Under 35', '35-49', '50-65', 'Over 65'] |
| 33 | +bottom = 1 |
35 | 34 | width = .2
|
36 |
| -colors = [[.1, .3, .5], [.1, .3, .3], [.1, .3, .7], [.1, .3, .9]] |
37 | 35 |
|
38 |
| -for j in range(len(ratios)): |
39 |
| - height = ratios[j] |
40 |
| - ax2.bar(xpos, height, width, bottom=bottom, color=colors[j]) |
41 |
| - ypos = bottom + ax2.patches[j].get_height() / 2 |
42 |
| - bottom += height |
43 |
| - ax2.text(xpos, ypos, "%d%%" % (ax2.patches[j].get_height() * 100), |
44 |
| - ha='center') |
| 36 | +# Adding from the top matches the legend. |
| 37 | +for j, (height, label) in enumerate(reversed([*zip(age_ratios, age_labels)])): |
| 38 | + bottom -= height |
| 39 | + bc = ax2.bar(0, height, width, bottom=bottom, color='C0', label=label, |
| 40 | + alpha=0.1 + 0.25 * j) |
| 41 | + ax2.bar_label(bc, labels=[f"{height:.0%}"], label_type='center') |
45 | 42 |
|
46 | 43 | ax2.set_title('Age of approvers')
|
47 |
| -ax2.legend(('50-65', 'Over 65', '35-49', 'Under 35')) |
| 44 | +ax2.legend() |
48 | 45 | ax2.axis('off')
|
49 | 46 | ax2.set_xlim(- 2.5 * width, 2.5 * width)
|
50 | 47 |
|
51 | 48 | # use ConnectionPatch to draw lines between the two plots
|
52 |
| -# get the wedge data |
53 |
| -theta1, theta2 = ax1.patches[0].theta1, ax1.patches[0].theta2 |
54 |
| -center, r = ax1.patches[0].center, ax1.patches[0].r |
55 |
| -bar_height = sum([item.get_height() for item in ax2.patches]) |
| 49 | +theta1, theta2 = wedges[0].theta1, wedges[0].theta2 |
| 50 | +center, r = wedges[0].center, wedges[0].r |
| 51 | +bar_height = sum(age_ratios) |
56 | 52 |
|
57 | 53 | # draw top connecting line
|
58 | 54 | x = r * np.cos(np.pi / 180 * theta2) + center[0]
|
|
0 commit comments