@@ -29,35 +29,28 @@ def hat_graph(ax, xlabels, values, group_labels):
29
29
The group labels displayed in the legend.
30
30
"""
31
31
32
- def label_bars (heights , rects ):
33
- """Attach a text label on top of each bar."""
34
- for height , rect in zip (heights , rects ):
35
- ax .annotate (f'{ height } ' ,
36
- xy = (rect .get_x () + rect .get_width () / 2 , height ),
37
- xytext = (0 , 4 ), # 4 points vertical offset.
38
- textcoords = 'offset points' ,
39
- ha = 'center' , va = 'bottom' )
40
-
41
32
values = np .asarray (values )
42
- x = np .arange (values .shape [1 ])
43
- ax .set_xticks (x , labels = xlabels )
44
- spacing = 0.3 # spacing between hat groups
45
- width = (1 - spacing ) / values .shape [0 ]
46
- heights0 = values [0 ]
47
- for i , (heights , group_label ) in enumerate (zip (values , group_labels )):
48
- style = {'fill' : False } if i == 0 else {'edgecolor' : 'black' }
49
- rects = ax .bar (x - spacing / 2 + i * width , heights - heights0 ,
50
- width , bottom = heights0 , label = group_label , ** style )
51
- label_bars (heights , rects )
33
+ color_cycle_colors = plt .rcParams ['axes.prop_cycle' ].by_key ()['color' ]
34
+
35
+ # Draw the hats
36
+ bars = ax .grouped_bar (
37
+ (values - values [0 ]).T , bottom = values [0 ], tick_labels = xlabels ,
38
+ labels = group_labels , edgecolor = 'black' , group_spacing = 0.8 ,
39
+ colors = ['none' ] + color_cycle_colors )
52
40
41
+ # Attach a text label on top of each bar
42
+ for bc , heights in zip (bars .bar_containers , values ):
43
+ ax .bar_label (bc , heights , padding = 4 )
53
44
54
- # initialise labels and a numpy array make sure you have
45
+
46
+ # Initialise labels and a numpy array make sure you have
55
47
# N labels of N number of values in the array
56
48
xlabels = ['I' , 'II' , 'III' , 'IV' , 'V' ]
57
49
playerA = np .array ([5 , 15 , 22 , 20 , 25 ])
58
50
playerB = np .array ([25 , 32 , 34 , 30 , 27 ])
59
51
60
- fig , ax = plt .subplots ()
52
+ fig , ax = plt .subplots (layout = 'constrained' )
53
+
61
54
hat_graph (ax , xlabels , [playerA , playerB ], ['Player A' , 'Player B' ])
62
55
63
56
# Add some text for labels, title and custom x-axis tick labels, etc.
@@ -67,7 +60,6 @@ def label_bars(heights, rects):
67
60
ax .set_title ('Scores by number of game and players' )
68
61
ax .legend ()
69
62
70
- fig .tight_layout ()
71
63
plt .show ()
72
64
# %%
73
65
#
@@ -76,8 +68,8 @@ def label_bars(heights, rects):
76
68
# The use of the following functions, methods, classes and modules is shown
77
69
# in this example:
78
70
#
79
- # - `matplotlib.axes.Axes.bar ` / `matplotlib.pyplot.bar `
80
- # - `matplotlib.axes.Axes.annotate ` / `matplotlib.pyplot.annotate `
71
+ # - `matplotlib.axes.Axes.grouped_bar ` / `matplotlib.pyplot.grouped_bar `
72
+ # - `matplotlib.axes.Axes.bar_label ` / `matplotlib.pyplot.bar_label `
81
73
#
82
74
# .. tags::
83
75
#
0 commit comments