Skip to content

Commit 239dcf3

Browse files
committed
ENH: Add properties position_centers and tops to BarContainer
1 parent e36bffb commit 239dcf3

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

lib/matplotlib/container.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,26 @@ def __init__(self, patches, errorbar=None, *, datavalues=None,
7373
self.orientation = orientation
7474
super().__init__(patches, **kwargs)
7575

76+
@property
77+
def tops(self):
78+
"""Return the values at the upper end of the bars."""
79+
if self.orientation == 'vertical':
80+
return [p.get_y() + p.get_height() for p in self.patches]
81+
elif self.orientation == 'horizontal':
82+
return [p.get_x() + p.get_width() for p in self.patches]
83+
else:
84+
raise ValueError("Orientation must be 'vertical' or 'horizontal'.")
85+
86+
@property
87+
def position_centers(self):
88+
"""Return the centers of bar positions."""
89+
if self.orientation == 'vertical':
90+
return [p.get_x() + p.get_width() / 2 for p in self.patches]
91+
elif self.orientation == 'horizontal':
92+
return [p.get_y() + p.get_height() / 2 for p in self.patches]
93+
else:
94+
raise ValueError("Orientation must be 'vertical' or 'horizontal'.")
95+
7696

7797
class ErrorbarContainer(Container):
7898
"""

lib/matplotlib/tests/test_container.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import numpy as np
2+
from numpy.testing import assert_array_equal
23
import matplotlib.pyplot as plt
34

45

@@ -35,3 +36,18 @@ def test_nonstring_label():
3536
# Test for #26824
3637
plt.bar(np.arange(10), np.random.rand(10), label=1)
3738
plt.legend()
39+
40+
41+
def test_barcontainer_position_centers_and_tops():
42+
fig, ax = plt.subplots()
43+
pos = [1, 2, 4]
44+
bottoms = np.array([1, 5, 3])
45+
heights = np.array([2, 3, 4])
46+
47+
container = ax.bar(pos, heights, bottom=bottoms)
48+
assert_array_equal(container.position_centers, pos)
49+
assert_array_equal(container.tops, bottoms + heights)
50+
51+
container = ax.barh(pos, heights, left=bottoms)
52+
assert_array_equal(container.position_centers, pos)
53+
assert_array_equal(container.tops, bottoms + heights)

0 commit comments

Comments
 (0)