如何在数据不是周期性的情况下绘制堆积的条形图

时间:2017-07-21 19:31:14

标签: python numpy matplotlib plot bar-chart

我有一个包含索引值的numpy数组Xs和一个包含hegihts的其他数组heights。如果Xs中缺少某些索引(我希望图中有空格),我可以如何优雅地绘制条形图,有些存在多次(在这种情况下我想要单独的,堆叠的矩形) )

enter image description here

我天真的解决方案包括2个for循环,获取第n个元素,创建多个Yaxis,然后使用另一个for循环将它们相互绘制,并自动堆叠。是否有更方便的numpy / matplotlib函数来处理我的数据?

import numpy as np
import matplotlib.pyplot as plt
Xs=np.array([0,1,1,1,3,4,4,6,6,6,7,8,9])
heights = np.array([10,9,8,5,7,6,4,3,2,1,1,12,1])
values, counts = np.unique(Xs, return_counts=True)
print (values, counts, max(counts))

WholeY=[]
smallY=np.zeros(max(Xs)+1)  

for freq in range(1,max(counts)+1): 
    for val, cnt in zip(values, counts):
        if cnt >= freq:
            index = np.where(Xs==val)[0][freq-1]
            smallY[val] = heights[index]
    WholeY.append(smallY)
    smallY=np.zeros(max(Xs)+1) 

fig, ax = plt.subplots()
## stack them on each other automatically, create init bottom:
previousBars=np.zeros_like(smallY)
for smallY in WholeY:
    currentBars=ax.bar(np.arange(len(smallY)),smallY, bottom=previousBars)
    previousBars=smallY
plt.show()

1 个答案:

答案 0 :(得分:1)

使用pandas可能很方便。不确定这是否是您正在寻找的:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

Xs=np.array([0,1,1,1,3,4,4,6,6,6,7,8,9])
heights = np.array([10,9,8,5,7,6,4,3,2,1,1,12,1])

# Make an empty template with missing indexes included
g = {k:pd.Series() for k in range(max(Xs)+1)}
df = pd.DataFrame(heights, index=Xs)
# Get heights array for each index with groupby method and update corresponding entries in g
df.groupby(df.index).apply(lambda x: g.update({x.name: x[0].reset_index(drop=True)}))
# Plot stacked bar graph from pandas DataFrame
# Fill in empty values with 0 so that there will be an empty space for missing indexes
pd.DataFrame(g).T.fillna(0).plot.bar(stacked=True, legend=False)
plt.show()

enter image description here