我有一个包含索引值的 numpy 数组 Xs
,还有一个包含 hegihts 的数组 heights
。当 Xs
中缺少某些索引(我希望图中有一个空白区域)时,我如何根据这些值优雅地绘制条形图,有些索引多次出现(我想要单独的堆叠矩形在那种情况下)
我天真的解决方案包括 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()
最佳答案
使用 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()
关于python - 当数据不是周期性的时,如何绘制基于堆叠的条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45245398/