I have a numpy array Xs containing index values, and an other array heights containing hegihts. How can I plot a barchart, from these values elegantly, when some indexes are missing from Xs (I want an empty space there in the plot), some are present multiple times ( I want separate, stacked rectangles in that case)
My naive solution includes 2 for loops, getting the n-th elements, creating multiple Yaxis, and then plot them on each other using another for loop, with automatic stacking. Is there a more convinient numpy/matplotlib function to handle my data?
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()
