Skip to content

Commit 44e3dcd

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

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
``BarContainer`` properties
2+
---------------------------
3+
`.BarContainer` gained two properties: `~.BarContainer.position_centers`
4+
and `~.BarContainer.tops`.

lib/matplotlib/container.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,34 @@ 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+
"""
79+
Return the values at the upper end of the bars.
80+
81+
.. versionadded:: 3.11
82+
"""
83+
if self.orientation == 'vertical':
84+
return [p.get_y() + p.get_height() for p in self.patches]
85+
elif self.orientation == 'horizontal':
86+
return [p.get_x() + p.get_width() for p in self.patches]
87+
else:
88+
raise ValueError("Orientation must be 'vertical' or 'horizontal'.")
89+
90+
@property
91+
def position_centers(self):
92+
"""
93+
Return the centers of bar positions.
94+
95+
.. versionadded:: 3.11
96+
"""
97+
if self.orientation == 'vertical':
98+
return [p.get_x() + p.get_width() / 2 for p in self.patches]
99+
elif self.orientation == 'horizontal':
100+
return [p.get_y() + p.get_height() / 2 for p in self.patches]
101+
else:
102+
raise ValueError("Orientation must be 'vertical' or 'horizontal'.")
103+
76104

77105
class ErrorbarContainer(Container):
78106
"""

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)