python堆积图的画法_Matplotlib: 堆积柱状图的画法

两层堆积import numpy as np

import matplotlib.pyplot as plt

y1 = np.array([1,2,3,4])

y2 = np.array([1,1,1,1])

x = np.array([2009,2010,2011,2012])

plt.figure(figsize=(4,4))

plt.bar(x, y1, label='a')

plt.bar(x, y2, bottom=y1, label='b')

leg = plt.legend(loc='lower center',frameon=False,bbox_to_anchor=(0.5, -0.18),ncol=2)

plt.show()

效果

wAAACwAAAAAAQABAEACAkQBADs=

多层堆积

关键点在于在画yi时,要计算出yi之前所有数据的和作为bottom,例如:

y3的bottom为y1+y2

y4的bottom为y1+y2+y3import numpy as np

import matplotlib.pyplot as plt

y1 = np.array([1,2,3,4])

y2 = np.array([1,1,1,1])

y3 = np.array([2,1,2,3])

y = [y1, y2, y3]

y_c = np.cumsum(y, 0)

labels = ['a', 'b', 'c']

x = np.array([2009,2010,2011,2012])

plt.figure(figsize=(4,4.5))

for i in range(3):

if i == 0:

plt.bar(x, y[i], label=labels[i])

else:

plt.bar(x, y[i], bottom=y_c[i-1], label=labels[i])

leg = plt.legend(loc='lower center',frameon=False,bbox_to_anchor=(0.5, -0.18),ncol=3)

plt.show()

效果

wAAACwAAAAAAQABAEACAkQBADs=

https://www.jianshu.com/p/4af70ed49484

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页