|
3 | 3 | Barchart
|
4 | 4 | ========
|
5 | 5 |
|
6 |
| -A bar plot with errorbars and height labels on individual bars |
| 6 | +A bar plot with errorbars and height labels on individual bars. |
7 | 7 | """
|
8 | 8 | importnumpyasnp
|
9 | 9 | importmatplotlib.pyplotasplt
|
10 | 10 |
|
11 |
| -N=5 |
12 |
| -men_means= (20,35,30,35,27) |
13 |
| -men_std= (2,3,4,1,2) |
| 11 | +men_means,men_std= (20,35,30,35,27), (2,3,4,1,2) |
| 12 | +women_means,women_std= (25,32,34,20,25), (3,5,2,3,3) |
14 | 13 |
|
15 |
| -ind=np.arange(N)# the x locations for the groups |
16 |
| -width=0.35# the width of the bars |
| 14 | +ind=np.arange(len(men_means))# the x locations for the groups |
| 15 | +width=0.35# the width of the bars |
17 | 16 |
|
18 | 17 | fig,ax=plt.subplots()
|
19 |
| -rects1=ax.bar(ind,men_means,width,color='r',yerr=men_std) |
| 18 | +rects1=ax.bar(ind-width/2,men_means,width,yerr=men_std, |
| 19 | +color='SkyBlue',label='Men') |
| 20 | +rects2=ax.bar(ind+width/2,women_means,width,yerr=women_std, |
| 21 | +color='IndianRed',label='Women') |
20 | 22 |
|
21 |
| -women_means= (25,32,34,20,25) |
22 |
| -women_std= (3,5,2,3,3) |
23 |
| -rects2=ax.bar(ind+width,women_means,width,color='y',yerr=women_std) |
24 |
| - |
25 |
| -# add some text for labels, title and axes ticks |
| 23 | +# Add some text for labels, title and custom x-axis tick labels, etc. |
26 | 24 | ax.set_ylabel('Scores')
|
27 | 25 | ax.set_title('Scores by group and gender')
|
28 |
| -ax.set_xticks(ind+width/2) |
| 26 | +ax.set_xticks(ind) |
29 | 27 | ax.set_xticklabels(('G1','G2','G3','G4','G5'))
|
30 |
| - |
31 |
| -ax.legend((rects1[0],rects2[0]), ('Men','Women')) |
| 28 | +ax.legend() |
32 | 29 |
|
33 | 30 |
|
34 |
| -defautolabel(rects): |
| 31 | +defautolabel(rects,xpos='center'): |
35 | 32 | """
|
36 |
| - Attach a text label above each bar displaying its height |
| 33 | + Attach a text label above each bar in *rects*, displaying its height. |
| 34 | +
|
| 35 | + *xpos* indicates which side to place the text w.r.t. the center of |
| 36 | + the bar. It can be one of the following {'center', 'right', 'left'}. |
37 | 37 | """
|
| 38 | + |
| 39 | +xpos=xpos.lower()# normalize the case of the parameter |
| 40 | +ha= {'center':'center','right':'left','left':'right'} |
| 41 | +offset= {'center':0.5,'right':0.57,'left':0.43}# x_txt = x + w*off |
| 42 | + |
38 | 43 | forrectinrects:
|
39 | 44 | height=rect.get_height()
|
40 |
| -ax.text(rect.get_x()+rect.get_width()/2.,1.05*height, |
41 |
| -'%d'%int(height), |
42 |
| -ha='center',va='bottom') |
| 45 | +ax.text(rect.get_x()+rect.get_width()*offset[xpos],1.01*height, |
| 46 | +'{}'.format(height),ha=ha[xpos],va='bottom') |
| 47 | + |
43 | 48 |
|
44 |
| -autolabel(rects1) |
45 |
| -autolabel(rects2) |
| 49 | +autolabel(rects1,"left") |
| 50 | +autolabel(rects2,"right") |
46 | 51 |
|
47 | 52 | plt.show()
|