1
1
"""
2
- =============
3
- Barchart Demo
4
- =============
5
-
6
- Bar charts of many shapes and sizes with Matplotlib.
2
+ ===================================
3
+ Percentiles as horizontal bar chart
4
+ ===================================
7
5
8
6
Bar charts are useful for visualizing counts, or summary statistics
9
- with error bars. These examples show a few ways to do this with Matplotlib.
7
+ with error bars. Also see the :doc:`/gallery/lines_bars_and_markers/barchart`
8
+ or the :doc:`/gallery/lines_bars_and_markers/barh` example for simpler versions
9
+ of those features.
10
10
"""
11
11
12
- ###############################################################################
13
- # A bar plot with errorbars and height labels on individual bars.
14
-
15
- # Credit: Josh Hemann
16
-
17
- import numpy as np
18
- import matplotlib .pyplot as plt
19
- from matplotlib .ticker import MaxNLocator
20
- from collections import namedtuple
21
-
22
-
23
- men_means , men_std = (20 , 35 , 30 , 35 , 27 ), (2 , 3 , 4 , 1 , 2 )
24
- women_means , women_std = (25 , 32 , 34 , 20 , 25 ), (3 , 5 , 2 , 3 , 3 )
25
-
26
- ind = np .arange (len (men_means )) # the x locations for the groups
27
- width = 0.35 # the width of the bars
28
-
29
- fig , ax = plt .subplots ()
30
- rects1 = ax .bar (ind - width / 2 , men_means , width , yerr = men_std ,
31
- label = 'Men' )
32
- rects2 = ax .bar (ind + width / 2 , women_means , width , yerr = women_std ,
33
- label = 'Women' )
34
-
35
- # Add some text for labels, title and custom x-axis tick labels, etc.
36
- ax .set_ylabel ('Scores' )
37
- ax .set_title ('Scores by group and gender' )
38
- ax .set_xticks (ind )
39
- ax .set_xticklabels (('G1' , 'G2' , 'G3' , 'G4' , 'G5' ))
40
- ax .legend ()
41
-
42
-
43
- def autolabel (rects , xpos = 'center' ):
44
- """
45
- Attach a text label above each bar in *rects*, displaying its height.
46
-
47
- *xpos* indicates which side to place the text w.r.t. the center of
48
- the bar. It can be one of the following {'center', 'right', 'left'}.
49
- """
50
-
51
- ha = {'center' : 'center' , 'right' : 'left' , 'left' : 'right' }
52
- offset = {'center' : 0.5 , 'right' : 0.57 , 'left' : 0.43 } # x_txt = x + w*off
53
-
54
- for rect in rects :
55
- height = rect .get_height ()
56
- ax .text (rect .get_x () + rect .get_width () * offset [xpos ], 1.01 * height ,
57
- '{}' .format (height ), ha = ha [xpos ], va = 'bottom' )
58
-
59
-
60
- autolabel (rects1 , "left" )
61
- autolabel (rects2 , "right" )
62
-
63
- fig .tight_layout ()
64
-
65
12
66
13
###############################################################################
67
14
# This example comes from an application in which grade school gym
@@ -70,6 +17,13 @@ def autolabel(rects, xpos='center'):
70
17
# children did. To extract the plotting code for demo purposes, we'll
71
18
# just make up some data for little Johnny Doe...
72
19
20
+ import numpy as np
21
+ import matplotlib .pyplot as plt
22
+ from matplotlib .ticker import MaxNLocator
23
+ from collections import namedtuple
24
+
25
+ np .random .seed (42 )
26
+
73
27
Student = namedtuple ('Student' , ['name' , 'grade' , 'gender' ])
74
28
Score = namedtuple ('Score' , ['score' , 'percentile' ])
75
29
@@ -178,24 +132,25 @@ def plot_student_results(student, scores, cohort_size):
178
132
179
133
rankStr = attach_ordinal (width )
180
134
# The bars aren't wide enough to print the ranking inside
181
- if width < 5 :
135
+ if width < 40 :
182
136
# Shift the text to the right side of the right edge
183
- xloc = width + 1
137
+ xloc = 5
184
138
# Black against white background
185
139
clr = 'black'
186
140
align = 'left'
187
141
else :
188
142
# Shift the text to the left side of the right edge
189
- xloc = 0.98 * width
143
+ xloc = - 5
190
144
# White on magenta
191
145
clr = 'white'
192
146
align = 'right'
193
147
194
148
# Center the text vertically in the bar
195
149
yloc = rect .get_y () + rect .get_height () / 2
196
- label = ax1 .text (xloc , yloc , rankStr , horizontalalignment = align ,
197
- verticalalignment = 'center' , color = clr , weight = 'bold' ,
198
- clip_on = True )
150
+ label = ax1 .annotate (rankStr , xy = (width , yloc ), xytext = (xloc , 0 ),
151
+ textcoords = "offset points" ,
152
+ ha = align , va = 'center' ,
153
+ color = clr , weight = 'bold' , clip_on = True )
199
154
rect_labels .append (label )
200
155
201
156
# make the interactive mouse over give the bar title
@@ -219,3 +174,21 @@ def plot_student_results(student, scores, cohort_size):
219
174
220
175
arts = plot_student_results (student , scores , cohort_size )
221
176
plt .show ()
177
+
178
+
179
+ #############################################################################
180
+ #
181
+ # ------------
182
+ #
183
+ # References
184
+ # """"""""""
185
+ #
186
+ # The use of the following functions, methods and classes is shown
187
+ # in this example:
188
+
189
+ import matplotlib
190
+ matplotlib .axes .Axes .bar
191
+ matplotlib .pyplot .bar
192
+ matplotlib .axes .Axes .annotate
193
+ matplotlib .pyplot .annotate
194
+ matplotlib .axes .Axes .twinx
0 commit comments