有两个使用plt.bar的选项。
单个相邻条
您可以以分组的方式将条形彼此相邻绘制,您需要根据数组中的列数确定条形的位置。
import numpy as np
import matplotlib.pyplot as plt
data = np.array([[19, 14, 6, 36, 3],
[12, 12, 1, 32, 1],
[18, 25, 0, 33, 0],
[13, 19, 0, 32, 5],
[12, 14, 0, 33, 0],
[16, 14, 7, 30, 0],
[11, 18, 5, 31, 2],
[17, 11, 3, 46, 7]])
x = np.arange(data.shape[0])
dx = (np.arange(data.shape[1])-data.shape[1]/2.)/(data.shape[1]+2.)
d = 1./(data.shape[1]+2.)
fig, ax=plt.subplots()
for i in range(data.shape[1]):
ax.bar(x+dx[i],data[:,i], width=d, label="label {}".format(i))
plt.legend(framealpha=1).draggable()
plt.show()
堆叠的条形
或者您可以将条形堆叠在一起,这样条形的底部从前一个的顶部开始。
import numpy as np
import matplotlib.pyplot as plt
data = np.array([[19, 14, 6, 36, 3],
[12, 12, 1, 32, 1],
[18, 25, 0, 33, 0],
[13, 19, 0, 32, 5],
[12, 14, 0, 33, 0],
[16, 14, 7, 30, 0],
[11, 18, 5, 31, 2],
[17, 11, 3, 46, 7]])
x = np.arange(data.shape[0])
fig, ax=plt.subplots()
for i in range(data.shape[1]):
bottom=np.sum(data[:,0:i], axis=1)
ax.bar(x,data[:,i], bottom=bottom, label="label {}".format(i))
plt.legend(framealpha=1).draggable()
plt.show()