kitchenprinzessin kitchenprinzessin - 1 year ago 106
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):'ggplot')
ax=, title=title,figsize=(11, 7));
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 Source

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.


0    0.40
1    0.20
2    0.11
3    0.17
4    0.15
dtype: float64
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download