Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit db70ca1

Browse files
Create hat_graph.py
1 parent 2855691 commit db70ca1

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"""
2+
===============================
3+
Hat Graph with labels
4+
===============================
5+
This example shows a how to create a hat graph and how to annotate with labels.
6+
"""
7+
import matplotlib
8+
import numpy as np
9+
import matplotlib.pyplot as plt
10+
# initialise labels and a numpy array make sure you have N labels of N number of values in the array
11+
labels = ['I', 'II','III','IV','V']
12+
playerA = np.array([5, 15, 22, 20, 25])
13+
playerB = np.array([25, 32, 34, 30, 27])
14+
x = np.arange(len(labels))
15+
width = 0.35
16+
17+
fig, ax = plt.subplots()
18+
rects1 = ax.bar(x - width/2, np.zeros_like(playerA), width,
19+
bottom=playerA, label='Player A', fill=False)
20+
rects2 = ax.bar(x + width/2, playerB - playerA, width,
21+
bottom=playerA, label='Player B',edgecolor='black')
22+
#-----------------------------------------------------------------------------------------
23+
# Add some text for labels, title and custom x-axis tick labels, etc.
24+
ax.set_ylim(0,60)
25+
ax.set_ylabel('Score')
26+
ax.set_title('Scores by number of game and Players')
27+
ax.set_xticks(x)
28+
ax.set_xticklabels(labels)
29+
ax.legend()
30+
ax.set_xlabel('Games')
31+
#--------------------------------------------------------------------------------------------
32+
def Label(heights,rects):
33+
"""Attach a text label on top of each bar. """
34+
i=0
35+
for rect in rects:
36+
height=int(heights[i])
37+
i+=1
38+
ax.annotate('{}'.format(height),
39+
xy=(rect.get_x() + rect.get_width() / 2, height),
40+
xytext=(0, 4), # 4 points vertical offset.
41+
textcoords="offset points",
42+
ha='center', va='bottom')
43+
Label(playerA,rects1)
44+
Label(playerB,rects2)
45+
fig.tight_layout()
46+
plt.show()
47+
#############################################################################
48+
#
49+
# ------------
50+
#
51+
# References
52+
# """"""""""
53+
#
54+
# The use of the following functions, methods and classes is shown
55+
# in this example:
56+
matplotlib.axes.Axes.bar
57+
matplotlib.pyplot.bar
58+
matplotlib.axes.Axes.annotate
59+
matplotlib.pyplot.annotate

0 commit comments

Comments
 (0)