使用Matplotlib绘制柱状图

   主要讲解如何使用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()

png

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()

png

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()

png

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()

png

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值