@@ -29,35 +29,28 @@ def hat_graph(ax, xlabels, values, group_labels):
2929 The group labels displayed in the legend.
3030 """
3131
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-
4132 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 )
5240
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 )
5344
54- # initialise labels and a numpy array make sure you have
45+
46+ # Initialise labels and a numpy array make sure you have
5547# N labels of N number of values in the array
5648xlabels = ['I' , 'II' , 'III' , 'IV' , 'V' ]
5749playerA = np .array ([5 , 15 , 22 , 20 , 25 ])
5850playerB = np .array ([25 , 32 , 34 , 30 , 27 ])
5951
60- fig , ax = plt .subplots ()
52+ fig , ax = plt .subplots (layout = 'constrained' )
53+
6154hat_graph (ax , xlabels , [playerA , playerB ], ['Player A' , 'Player B' ])
6255
6356# Add some text for labels, title and custom x-axis tick labels, etc.
@@ -67,7 +60,6 @@ def label_bars(heights, rects):
6760ax .set_title ('Scores by number of game and players' )
6861ax .legend ()
6962
70- fig .tight_layout ()
7163plt .show ()
7264# %%
7365#
@@ -76,8 +68,8 @@ def label_bars(heights, rects):
7668# The use of the following functions, methods, classes and modules is shown
7769# in this example:
7870#
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 `
8173#
8274# .. tags::
8375#
0 commit comments