0

I have the following dataframe

import pandas as pd
from plotnine import *

df = pd.DataFrame({
    'variable': ['gender', 'gender', 'age', 'age', 'age', 'income', 'income', 'income', 'income'],
    'category': ['Female', 'Male', '1-24', '25-54', '55+', 'Lo', 'Lo-Med', 'Med', 'High'],
    'value': [60, 40, 50, 30, 20, 10, 25, 25, 40],
})
df['variable'] = pd.Categorical(df['variable'], categories=['gender', 'age', 'income'])

An I am using the following code to get the stacked bar plot

(ggplot(df, aes(x='variable', y='value', fill='category'))
 + geom_col()
)

The above code was taken from here

How can I put labels, ( in this case the values ), in the middle of each category at each bar ?

quant
  • 4,062
  • 5
  • 29
  • 70
  • Any reason you wouldn't want matplotlib? In case you are flexible, [this](https://stackoverflow.com/questions/30228069/how-to-display-the-value-of-the-bar-on-each-bar-with-pyplot-barh) solution might help you. Also, the link you shared consists of examples where they annotate the bars with values on the top if you scroll down – Sheldore Oct 05 '18 at 10:22
  • the labels are on top of the bars, and not in the middle of the stacked bars :( – quant Oct 15 '18 at 10:31

1 Answers1

0

You can do that just like in ggplot2 (plotnine replicates it with high fidelity), mapping "value" to labels in aesthetics and adding geom_text (with stack positioning, in this example vertically centered):

(ggplot(df, aes(x='variable', y='value', fill='category', label='value'))
 + geom_col()
 + geom_text(position=position_stack(vjust=0.5))
)

barplot with labels

See this answer for more detailed explanations on this feature in the original ggplot2.

krassowski
  • 13,598
  • 4
  • 60
  • 92