kitchenprinzessin kitchenprinzessin - 4 months ago 17
Python Question

How to add label on top of columns in a python stacked bar?

I have created a stacked bar from pandas dataframe (df):

plt.style.use('ggplot')
ax= df.plot.bar(stacked=True, title=title,figsize=(11, 7));
ax.set_ylabel("Score")
ax.set_xlabel("Item")
ax.set_ylim([0,1.4])
ax.set_xticklabels(labels=df.index,rotation=0,minor=False)
labels = ["label%d" % i for i in range(9)]
rects = ax.patches

for rect, label in zip(rects, labels):
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2, height, label, ha='center', va='bottom')


enter image description here
How can I display a label on top of the columns in the bar?

Answer

You can use the sum() function to sum values of all columns on a per-x-basis in a pandas dataframe:

df = pd.DataFrame({
    'keyword':  [.2, .08, .02, 0, .15],
    'research': [.2, .12, .09, .17, 0]
})

dy = sum(df[c] for c in df.keys())

The resulting values in dy can then serve as the y-offset for your labels.

print(dy)

0    0.40
1    0.20
2    0.11
3    0.17
4    0.15
dtype: float64
Comments