BUG: stacked bar graphs show invalid label position due to invalid rectangle bottom when data is 0 · Issue #59429 · pandas-dev/pandas (original) (raw)

Pandas version checks

Reproducible Example

import pandas as pd import matplotlib.pyplot as plt permutations = [(a,b,c) for a in range(2) for b in range(2) for c in range(3)] data = [ {'i': i, 'a':a, 'b':b, 'c':c, 't': a+b+c} for i, (a,b,c) in enumerate(permutations) ] df = pd.DataFrame.from_dict(data) ax = df[['a','b', 'c']].plot.bar(stacked=True) bl = ax.bar_label(ax.containers[-1], df['t']) plt.show()

Issue Description

if the top part of the stacked plot has data value 0, the bar-label does not appear on top, but at the bottom of the bar.
grafik

Further debugging shows that all bars with data = 0 have their y position set to 0.0. They should have the top of the bar below as their bottom = y.

Expected Behavior

Bar-Labels should be positioned on top for all stacks.

grafik

this behaviour can be produced by correcting the y positions of the defective bars

def correct_stack(container, info=False):
    """ correct the y positions of stacked bars with 0 height

    This is needed because the y position is calculated wrongly when data value is 0 on stacked bars created by Pandas plot.bar.
    """
    # Attention, since we start at row 1, r shows to the row below - which we need
    for r, row in enumerate(container[1:]):
        for b, bar in enumerate(row):
            (my_x, my_y), my_height = bar.xy, bar.get_height()
            # note that r show to the bar below the current bar, and c is the stack
            support = container[r][b]    # this is the bar we are resting on top of
            (s_x, s_y), s_height = support.xy, support.get_height()
            if info:
                print(f"bar at row: {r+1}, col: {b}: ({my_x}, {my_y}) - {my_height} resting on top of ({s_x, s_y}) - {s_height}")
            if my_y < s_y + s_height:
                print(f"bar at row: {r+1}, col: {b}: {my_y = } is lower than expected {s_y + s_height}")
                bar.xy = (my_x, s_y + s_height)

ax2 = df[['a','b','c']].plot.bar(stacked=True)
correct_stack(ax2.containers)
bl = ax2.bar_label(ax2.containers[-1], df['t'])
plt.show()

Installed Versions

INSTALLED VERSIONS

commit : d9cdd2e
python : 3.11.9.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version : 10.0.22631
machine : AMD64
processor : Intel64 Family 6 Model 186 Stepping 2, GenuineIntel
byteorder : little
LC_ALL : None
LANG : None
LOCALE : de_DE.cp1252

pandas : 2.2.2
numpy : 2.0.1
pytz : 2024.1
dateutil : 2.9.0.post0
setuptools : 65.5.0
pip : 24.2
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.1.4
IPython : 8.26.0
pandas_datareader : None
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : 4.12.3
bottleneck : None
dataframe-api-compat : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.9.1
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyreadstat : None
python-calamine : None
pyxlsb : None
s3fs : None
scipy : 1.14.0
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : None
tzdata : 2024.1
qtpy : None
pyqt5 : None