主要讲解如何使用Matplotlib绘制柱状图…
#
import numpy as np
import matplotlib.pyplot as plt
Type 1
a = (20, 30, 30, 35, 27)
b = (25, 40, 34, 20, 25)
ind = np.arange(len(a))
width = 0.35
p1 = plt.bar(ind, a, width)
p2 = plt.bar(ind,b, width, bottom=a)
label = [str(i) for i in range(4)]
label.append('0')
plt.xticks([i for i in range(len(a))], label)
plt.legend((p1[0], p2[0]), ('a', 'b'))
plt.title('Type 1')
plt.show()
Type 2
x1 = (20, 30, 30, 35, 27)
x2 = (25, 40, 34, 20, 25)
x3 = [40, 25, 35, 40, 30]
ind = np.arange(len(x1))
width = 0.35
p1 = plt.bar(ind, x1, width)
p2 = plt.bar(ind, x2, width, bottom=x1)
temp_x1_x2 = [x1[i]+x2[i] for i in range(len(x1))]
p3 = plt.bar(ind, x3, width, bottom=temp_x1_x2)
plt.legend((p1[0],p2[0],p3[0]),('x1','x2','x3'))
plt.title('Type 2')
plt.show()
Type 3
c = (20, 30, 30, 35, 27)
d = (25, -40, 34, -20, 25)
ind = np.arange(len(a))
width = 0.35
index = [i for i in range(len(d)) if d[i]<0]
bottom = np.array(c)
for i in index:
bottom[i] = 0
p1 = plt.bar(ind, c, width)
p2 = plt.bar(ind, d, width, bottom=bottom)
plt.legend((p1[0], p2[0]), ('c','d'))
plt.title('Type 3')
plt.show()
Type 4
y1 = (20, 30, 30, 35, 27)
y2 = (25, 40, 34, 20, 25)
y3 = [-40, 25, -35, 40, -30]
ind = np.arange(len(y1))
width = 0.35
index = [i for i in range(len(y3)) if y3[i]<0]
temp_y1_y2 = [y1[i]+y2[i] for i in range(len(y1))]
bottom = np.array(temp_y1_y2)
for i in index:
bottom[i] = 0
p1 = plt.bar(ind, y1, width)
p2 = plt.bar(ind, y2, width, bottom=y1)
p3 = plt.bar(ind, y3, width, bottom=bottom)
plt.legend((p1[0],p2[0],p3[0]),('y1','y2','y3'))
plt.title('Type 4')
plt.show()