画并排柱状图和堆叠柱状图

import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

mpl.rcParams["font.sans-serif"] = ["SimHei"]
mpl.rcParams["axes.unicode_minus"] = False

pos_num = [108, 36, 121, 109, 147, 96, 53, 123, 73, 117, 37, 94, 321, 109, 318, 147]
neg_num = [11097, 10015, 12439, 12125, 7422, 4777, 10262, 10841, 13326, 10465, 5617, 11251, 13474, 11475, 6710, 9027]
labels = ["设备" + str(i) for i in range(1, 17)]

#设置各种参数
xlocation =  np.linspace(1, len(pos_num) * 0.6, len(pos_num)) #len(data个序列)
print(xlocation)

height01 = pos_num
height02 = neg_num
width = 0.2
color01='red'
color02 = '#0000A3'

"""
    画并排柱状图

"""
fig = plt.figure(figsize=(10,8)) #指定了图的名称 和画布的大小
fig.tight_layout()
ax1 = fig.add_subplot(111) #2X2 中的第一个子图
# plt.suptitle('不同设备正负样本数量', fontsize=15) # 添加图标题
#画图
rects01 = ax1.bar(xlocation, height01, width = 0.2, color=color01,linewidth=1,alpha=0.8)
rects02 = ax1.bar(xlocation+0.2,height02 ,width = 0.2, color=color02,linewidth=1,alpha=0.8)
#添加x轴标签
plt.xticks(xlocation+0.15,labels, fontsize=12 ,rotation = 20)  # 横坐标轴标签 rotation x轴标签旋转的角度
# 横纵坐标分别代表什么
plt.xlabel(u"设备", fontsize=15, labelpad=10)
plt.ylabel(u"样本数量", fontsize=15, labelpad=10)
#图例
ax1.legend((rects01,rects02),( u"正样本",u"负样本"), fontsize=15)  # 图例
# 添加数据标签
for r1,r2 ,amount01,amount02 in zip(rects01, rects02, pos_num, neg_num):
        h01 = r1.get_height()
        h02 = r2.get_height()
        plt.text(r1.get_x() - 0.11, h01, amount01, fontsize=13, va ='bottom')  # 添加正样本数量标签
        plt.text(r2.get_x() - 0.11, h02 , amount02, fontsize=13, va='bottom')  # 添加负样本数量标签
plt.show()
exit()

"""
    画堆叠柱状图

"""
data = np.array([[10., 30., 19., 22.],
                [5., 18., 15., 20.],
                [4., 6., 3., 5.]])
color_list = ['b', 'g', 'r']
ax2 = fig.add_subplot(222)
X = np.arange(data.shape[1])
print(X)
for i in range(data.shape[0]):#i表示list的索引值
    ax2.bar(X, data[i],
         width=0.2,
         bottom = np.sum(data[:i], axis = 0),
         color = color_list[i % len(color_list)],
            alpha =0.5
            )
plt.savefig('zhifangtu.png',dpi=120,bbox_inches='tight')

你可能感兴趣的:(笔记杂)