pythonpandasdataframeplotchaining

Python : Pandas Chaining : How to add text to the plot?


How to add text/label to a bar plot, when using pandas chaining ? Below is how I'm plotting without the label.

(
  df
  .groupby(['col1','col2'], dropna=False)
  [['col1', 'col2']]
  .size()
  .unstack()
  .plot(kind='bar', figsize = (8,8))
 )

The unstacked data frame (right before .plot in the above code) has data as below.

col2    1.0     2.0     3.0     4.0     NaN
col1
 1.0    514    1922    7827   18877    1966
 2.0    NaN     NaN     NaN     NaN    2018
 NaN     21      20      59      99    5570

The plot is as below: enter image description here

I would like to have the numbers displayed on top of the bars. Please advice. Thank you.


Solution

  • You have to get the output of your chaining (return an Axes instance):

    ax = (df.groupby(['col1', 'col2'], dropna=False)[['col1', 'col2']]
            .size().unstack()
            .plot(kind='bar', figsize=(8, 8)))
    
    for bars in ax.containers:
        ax.bar_label(bars)
    

    Output:

    enter image description here

    Update

    I'm using 3.3.2 and cannot upgrade due to system restrictions

    for rect in ax.patches:
        height = rect.get_height()
        ax.annotate(r'{:d}'.format(int(height)),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),
                    textcoords="offset points",
                    ha='center', va='bottom')