Skip to content

Commit b5e62ef

Browse files
authored
BUG: Fix #59429 stacked bar label position (#60211)
1 parent 04432f5 commit b5e62ef

File tree

3 files changed

+12
-1
lines changed

3 files changed

+12
-1
lines changed

doc/source/whatsnew/v3.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -711,6 +711,7 @@ Period
711711
Plotting
712712
^^^^^^^^
713713
- Bug in :meth:`.DataFrameGroupBy.boxplot` failed when there were multiple groupings (:issue:`14701`)
714+
- Bug in :meth:`DataFrame.plot.bar` with ``stacked=True`` where labels on stacked bars with zero-height segments were incorrectly positioned at the base instead of the label position of the previous segment (:issue:`59429`)
714715
- Bug in :meth:`DataFrame.plot.line` raising ``ValueError`` when set both color and a ``dict`` style (:issue:`59461`)
715716
- Bug in :meth:`DataFrame.plot` that causes a shift to the right when the frequency multiplier is greater than one. (:issue:`57587`)
716717
- Bug in :meth:`Series.plot` with ``kind="pie"`` with :class:`ArrowDtype` (:issue:`59192`)

pandas/plotting/_matplotlib/core.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1960,7 +1960,7 @@ def _make_plot(self, fig: Figure) -> None:
19601960
)
19611961
ax.set_title(label)
19621962
elif self.stacked:
1963-
mask = y > 0
1963+
mask = y >= 0
19641964
start = np.where(mask, pos_prior, neg_prior) + self._start_base
19651965
w = self.bar_width / 2
19661966
rect = self._plot(

pandas/tests/plotting/frame/test_frame.py

+10
Original file line numberDiff line numberDiff line change
@@ -774,6 +774,16 @@ def test_bar_nan_stacked(self):
774774
expected = [0.0, 0.0, 0.0, 10.0, 0.0, 20.0, 15.0, 10.0, 40.0]
775775
assert result == expected
776776

777+
def test_bar_stacked_label_position_with_zero_height(self):
778+
# GH 59429
779+
df = DataFrame({"A": [3, 0, 1], "B": [0, 2, 4], "C": [5, 0, 2]})
780+
ax = df.plot.bar(stacked=True)
781+
ax.bar_label(ax.containers[-1])
782+
expected = [8.0, 2.0, 7.0]
783+
result = [text.xy[1] for text in ax.texts]
784+
tm.assert_almost_equal(result, expected)
785+
plt.close("all")
786+
777787
@pytest.mark.parametrize("idx", [Index, pd.CategoricalIndex])
778788
def test_bar_categorical(self, idx):
779789
# GH 13019

0 commit comments

Comments
 (0)