如何创建非重叠堆积条形图?

时间:2017-05-15 10:33:24

标签: python matplotlib

我正在制作一个用于分析的堆积条形图,它正常工作,除了值重叠 enter image description here

在上面的过程中一切正常,除了订单价值重叠供应价值,但我希望供应堆叠超过订单

这是代码:

import matplotlib.pyplot as plt
import numpy as np

ind = np.arange(N)    
width = 0.3 

p1 = plt.bar(ind, order, width, color='yellow')
p2 = plt.bar(ind, supply, width, color='red', bottom=order)
p3 = plt.bar(ind, feedback, width, color='green', bottom=supply)

plt.xlabel('date')
plt.title('hello')
plt.yticks(np.arange(0,24000,6000))
plt.legend((p1[0], p2[0], p3[0]), ('order', 'supply', 'feedback'))

plt.show()

2 个答案:

答案 0 :(得分:0)

如果我理解你想要堆叠的问题

订单(黄色) - >供应(红色) - >垂直反馈(绿色)

您可以替换

p3 = plt.bar(ind, feedback, width, color='green', bottom=supply)

p3 = plt.bar(ind, feedback, width, color='green',bottom=[order[j] +supply[j] for j in range(len(order))])

这是类似的工作示例

import matplotlib.pyplot as plt
import numpy as np

ind = np.arange(5)    
width = 0.3 
order=[2,3,1,5,4]
supply=[3,4,2,6,5]
feedback=[1,1,1,1,1]

p1 = plt.bar(ind, order,width, color='yellow')
p2 = plt.bar(ind, supply, width, color='red',bottom=order)
p3 = plt.bar(ind, feedback, width, color='green',bottom=[order[j] +supply[j] for j in range(len(order))])

plt.xlabel('date')
plt.title('hello')
plt.legend((p1[0], p2[0], p3[0]), ('order', 'supply', 'feedback'))

plt.show()

答案 1 :(得分:0)

我会迭代数据并保持"底部"的运行标签。名单。例如:

import numpy as np
from matplotlib import pyplot as plt

ind = np.arange(5)
order = [1,2,3,1,1]
supply = [2,2,2,4,3]
feedback = [1,2,5,6,7]
width = 0.5
bottom = [0 for x in ind]
data = [order,supply,feedback]
colors = ["yellow","red","green"]
for color,item in zip(colors,data):
    plt.bar(ind,item,width,color=color,bottom=bottom)
    bottom = [a+b for a,b in zip(bottom,item)]

plt.show()

对于3件事,for循环可能有点过头了,但我认为你明白了。