Skip to content

BUG: Fix #59429 stacked bar label position #60211

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v2.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ Period

Plotting
^^^^^^^^
-
- 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`)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This note should be move to v3.0.0.rst.

Copy link
Member

@rhshadrach rhshadrach Nov 6, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2.3.0 is a "special" release in that we are not doing it from the main branch. We are only backporting certain PRs to the 2.3.x branch.

-

Groupby/resample/rolling
Expand Down
2 changes: 1 addition & 1 deletion pandas/plotting/_matplotlib/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1960,7 +1960,7 @@ def _make_plot(self, fig: Figure) -> None:
)
ax.set_title(label)
elif self.stacked:
mask = y > 0
mask = y >= 0
start = np.where(mask, pos_prior, neg_prior) + self._start_base
w = self.bar_width / 2
rect = self._plot(
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/plotting/frame/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -774,6 +774,15 @@ def test_bar_nan_stacked(self):
expected = [0.0, 0.0, 0.0, 10.0, 0.0, 20.0, 15.0, 10.0, 40.0]
assert result == expected

def test_bar_stacked_label_position_with_zero_height(self):
df = DataFrame({"A": [3, 0, 1], "B": [0, 2, 4], "C": [5, 0, 2]})
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you start this test with a comment referencing the GH issue. E.g. see the test immediately below for an example.

ax = df.plot.bar(stacked=True)
ax.bar_label(ax.containers[-1])
expected = [8.0, 2.0, 7.0]
result = [text.xy[1] for text in ax.texts]
tm.assert_almost_equal(result, expected)
plt.close("all")

@pytest.mark.parametrize("idx", [Index, pd.CategoricalIndex])
def test_bar_categorical(self, idx):
# GH 13019
Expand Down