Skip to content

Commit b2b8624

Browse files
committed
resolve suggested improvements
1 parent c8442e1 commit b2b8624

File tree

4 files changed

+76
-87
lines changed

4 files changed

+76
-87
lines changed

examples/lines_bars_and_markers/bar_label_demo.py

Lines changed: 44 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -32,42 +32,44 @@
3232
###############################################################################
3333
# Grouped bar chart
3434

35-
fig1, ax1 = plt.subplots()
35+
fig, ax = plt.subplots()
3636

37-
rects1 = ax1.bar(ind - width/2, menMeans, width, label='Men')
38-
rects2 = ax1.bar(ind + width/2, womenMeans, width, label='Women')
37+
rects1 = ax.bar(ind - width/2, menMeans, width, label='Men')
38+
rects2 = ax.bar(ind + width/2, womenMeans, width, label='Women')
3939

40-
ax1.set_ylabel('Scores')
41-
ax1.set_title('Scores by group and gender')
42-
ax1.set_xticks(ind)
43-
ax1.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
44-
ax1.legend()
40+
ax.axhline(0, color='grey', linewidth=0.8)
41+
ax.set_ylabel('Scores')
42+
ax.set_title('Scores by group and gender')
43+
ax.set_xticks(ind)
44+
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
45+
ax.legend()
4546

4647
# Basic labels
47-
ax1.bar_label(rects1)
48-
ax1.bar_label(rects2)
48+
ax.bar_label(rects1)
49+
ax.bar_label(rects2)
4950

5051
plt.show()
5152

5253
###############################################################################
5354
# Stacked bar plot with error bars
5455

55-
fig2, ax2 = plt.subplots()
56+
fig, ax = plt.subplots()
5657

57-
p1 = ax2.bar(ind, menMeans, width, yerr=menStd, label='Men')
58-
p2 = ax2.bar(ind, womenMeans, width,
59-
bottom=menMeans, yerr=womenStd, label='Women')
58+
p1 = ax.bar(ind, menMeans, width, yerr=menStd, label='Men')
59+
p2 = ax.bar(ind, womenMeans, width,
60+
bottom=menMeans, yerr=womenStd, label='Women')
6061

61-
ax2.set_ylabel('Scores')
62-
ax2.set_title('Scores by group and gender')
63-
ax2.set_xticks(ind)
64-
ax2.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
65-
ax2.legend()
62+
ax.axhline(0, color='grey', linewidth=0.8)
63+
ax.set_ylabel('Scores')
64+
ax.set_title('Scores by group and gender')
65+
ax.set_xticks(ind)
66+
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
67+
ax.legend()
6668

67-
# Label with 'center' mode instead of the default 'edge' mode
68-
ax2.bar_label(p1, mode='center')
69-
ax2.bar_label(p2, mode='center')
70-
ax2.bar_label(p2)
69+
# Label with position 'center' instead of the default 'edge'
70+
ax.bar_label(p1, position='center')
71+
ax.bar_label(p2, position='center')
72+
ax.bar_label(p2)
7173

7274
plt.show()
7375

@@ -83,38 +85,39 @@
8385
performance = 3 + 10 * np.random.rand(len(people))
8486
error = np.random.rand(len(people))
8587

86-
fig3, ax3 = plt.subplots()
88+
fig, ax = plt.subplots()
8789

88-
hbars1 = ax3.barh(y_pos, performance, xerr=error, align='center')
89-
ax3.set_yticks(y_pos)
90-
ax3.set_yticklabels(people)
91-
ax3.invert_yaxis() # labels read top-to-bottom
92-
ax3.set_xlabel('Performance')
93-
ax3.set_title('How fast do you want to go today?')
90+
hbars = ax.barh(y_pos, performance, xerr=error, align='center')
91+
ax.set_yticks(y_pos)
92+
ax.set_yticklabels(people)
93+
ax.invert_yaxis() # labels read top-to-bottom
94+
ax.set_xlabel('Performance')
95+
ax.set_title('How fast do you want to go today?')
9496

9597
# Label with specially formatted floats
96-
ax3.bar_label(hbars1, fmt='%.2f')
98+
ax.bar_label(hbars, fmt='%.2f')
99+
ax.set_xlim(right=15) # adjust xlim to fit labels
97100

98101
plt.show()
99102

100103
###############################################################################
101104
# Some of the more advanced things that one can do with bar labels
102105

103-
fig4, ax4 = plt.subplots()
106+
fig, ax = plt.subplots()
104107

105-
hbars2 = ax4.barh(y_pos, performance, xerr=error, align='center')
106-
ax4.set_yticks(y_pos)
107-
ax4.set_yticklabels(people)
108-
ax4.invert_yaxis() # labels read top-to-bottom
109-
ax4.set_xlabel('Performance')
110-
ax4.set_title('How fast do you want to go today?')
108+
hbars = ax.barh(y_pos, performance, xerr=error, align='center')
109+
ax.set_yticks(y_pos)
110+
ax.set_yticklabels(people)
111+
ax.invert_yaxis() # labels read top-to-bottom
112+
ax.set_xlabel('Performance')
113+
ax.set_title('How fast do you want to go today?')
111114

112115
# Label with given captions, custom padding, shifting and annotate option
113116
arrowprops = dict(color='b', arrowstyle="-|>",
114117
connectionstyle="angle,angleA=0,angleB=90,rad=20")
115-
116-
ax4.bar_label(hbars2, captions=['±%.2f' % e for e in error],
117-
padding=30, shifting=20, arrowprops=arrowprops, color='b')
118+
ax.bar_label(hbars, captions=['±%.2f' % e for e in error],
119+
padding=30, shifting=20, arrowprops=arrowprops, color='b')
120+
ax.set_xlim(right=17)
118121

119122
plt.show()
120123

lib/matplotlib/axes/_axes.py

Lines changed: 30 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -2381,8 +2381,8 @@ def bar(self, x, height, width=0.8, bottom=None, *, align="center",
23812381

23822382
self._request_autoscale_view()
23832383

2384-
bar_container = BarContainer(patches, errorbar, orientation,
2385-
label=label)
2384+
bar_container = BarContainer(patches, errorbar,
2385+
orientation=orientation, label=label)
23862386
self.add_container(bar_container)
23872387

23882388
if tick_labels is not None:
@@ -2498,12 +2498,13 @@ def barh(self, y, width, height=0.8, left=None, *, align="center",
24982498
align=align, **kwargs)
24992499
return patches
25002500

2501-
def bar_label(self, container, captions=[], fmt="%g", mode="edge",
2502-
padding=None, shifting=0, autoscale=True, **kwargs):
2501+
def bar_label(self, container, captions=[], *, fmt="%g", position="edge",
2502+
padding=0, shifting=0, **kwargs):
25032503
"""
25042504
Label a bar plot.
25052505
25062506
Adds labels to bars in the given `.BarContainer`.
2507+
You may need to adjust the axis limits to fit the labels.
25072508
25082509
Parameters
25092510
----------
@@ -2514,40 +2515,33 @@ def bar_label(self, container, captions=[], fmt="%g", mode="edge",
25142515
A list of label texts, that should be displayed. If not given, the
25152516
label texts will be the data values formatted with *fmt*.
25162517
2517-
fmt : str, optional
2518-
A format string for the label. Default is '%g'
2518+
fmt : str, default: '%g'
2519+
A format string for the label.
25192520
2520-
mode : {'edge', 'center'}, optional, default: 'edge'
2521+
position : {'edge', 'center'}, default: 'edge'
25212522
Position of the label relative to the bar:
25222523
25232524
- 'edge': Placed at edge, the cumulative values will be shown.
25242525
- 'center': Placed at center, the individual values will be shown.
25252526
2526-
padding : float, optional
2527-
Space in points for label to leave the edge of the bar.
2528-
2529-
shifting : float, optional
2530-
Translation in points for label to leave the center of the bar.
2527+
padding : float, default: 0
2528+
Offset in points for label to shift in longitudinal direction.
25312529
2532-
autoscale : bool, optional
2533-
If ``True``, try to rescale to fit the labels. Default is ``True``.
2530+
shifting : float, default: 0
2531+
Offset in points for label to shift in lateral direction.
25342532
25352533
Returns
25362534
-------
25372535
annotations
25382536
A list of `.Text` instances for the labels.
25392537
"""
2540-
def nonefill(a, n):
2541-
return list(a) + [None] * (n - len(a))
2538+
def extend_with_none(iterable, length):
2539+
return list(iterable) + [None] * (length - len(iterable))
25422540

25432541
def sign(x):
25442542
return 1 if x >= 0 else -1
25452543

2546-
cbook._check_in_list(['edge', 'center'], mode=mode)
2547-
if mode == "edge":
2548-
padding = padding or 3
2549-
elif mode == "center":
2550-
padding = padding or 0
2544+
cbook._check_in_list(['edge', 'center'], position=position)
25512545

25522546
bars = container.patches
25532547
errorbar = container.errorbar
@@ -2559,10 +2553,10 @@ def sign(x):
25592553
barlinecols = lines[2]
25602554
barlinecol = barlinecols[0]
25612555
segments = barlinecol.get_segments()
2562-
errs = nonefill(segments, N)
2556+
errs = extend_with_none(segments, length=N)
25632557
else:
2564-
errs = nonefill([], N)
2565-
caps = nonefill(captions, N)
2558+
errs = extend_with_none([], length=N)
2559+
caps = extend_with_none(captions, length=N)
25662560

25672561
annotations = []
25682562
for bar, err, cap in zip(bars, errs, caps):
@@ -2584,49 +2578,41 @@ def sign(x):
25842578
elif orientation == "horizontal":
25852579
endpt = err[:, 0].max() if xc >= 0 else err[:, 0].min()
25862580

2587-
if mode == "center":
2581+
if position == "center":
25882582
value = sign(extrema) * length
2589-
elif mode == "edge":
2583+
elif position == "edge":
25902584
value = extrema
25912585

2592-
if mode == "center":
2586+
if position == "center":
25932587
xy = xc, yc
2594-
elif mode == "edge" and orientation == "vertical":
2588+
elif position == "edge" and orientation == "vertical":
25952589
xy = xc, endpt
2596-
elif mode == "edge" and orientation == "horizontal":
2590+
elif position == "edge" and orientation == "horizontal":
25972591
xy = endpt, yc
25982592

25992593
if orientation == "vertical":
26002594
xytext = shifting, sign(extrema) * padding
26012595
else:
26022596
xytext = sign(extrema) * padding, shifting
26032597

2604-
if mode == "center":
2598+
if position == "center":
26052599
ha, va = "center", "center"
2606-
elif mode == "edge" and orientation == "vertical" and yc >= 0:
2600+
elif position == "edge" and orientation == "vertical" and yc >= 0:
26072601
ha, va = "center", "bottom"
2608-
elif mode == "edge" and orientation == "vertical" and yc < 0:
2602+
elif position == "edge" and orientation == "vertical" and yc < 0:
26092603
ha, va = "center", "top"
2610-
elif mode == "edge" and orientation == "horizontal" and xc >= 0:
2604+
elif (
2605+
position == "edge" and orientation == "horizontal" and xc >= 0
2606+
):
26112607
ha, va = "left", "center"
2612-
elif mode == "edge" and orientation == "horizontal" and xc < 0:
2608+
elif position == "edge" and orientation == "horizontal" and xc < 0:
26132609
ha, va = "right", "center"
26142610

26152611
annotation = self.annotate(cap or fmt % value, xy, xytext,
26162612
textcoords="offset points",
26172613
ha=ha, va=va, **kwargs)
26182614
annotations.append(annotation)
26192615

2620-
if autoscale:
2621-
transform = self.transData.inverted()
2622-
renderer = self.figure.canvas.get_renderer()
2623-
corners = []
2624-
for text in annotations:
2625-
points = text.get_window_extent(renderer).get_points()
2626-
corners.append(transform.transform(points))
2627-
self.update_datalim(np.vstack(corners))
2628-
self.autoscale_view()
2629-
26302616
return annotations
26312617

26322618
@_preprocess_data()

lib/matplotlib/container.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ class BarContainer(Container):
6262
6363
"""
6464

65-
def __init__(self, patches, errorbar=None, orientation=None, **kwargs):
65+
def __init__(self, patches, errorbar=None, *, orientation=None, **kwargs):
6666
self.patches = patches
6767
self.errorbar = errorbar
6868
self.orientation = orientation

lib/matplotlib/tests/test_axes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6814,7 +6814,7 @@ def test_bar_label_location_center():
68146814
ax = plt.gca()
68156815
ys, widths = [1, 2], [3, -4]
68166816
rects = ax.barh(ys, widths)
6817-
labels = ax.bar_label(rects, mode='center')
6817+
labels = ax.bar_label(rects, position='center')
68186818
assert labels[0].xy == (widths[0] / 2, ys[0])
68196819
assert labels[0].get_ha() == 'center'
68206820
assert labels[0].get_va() == 'center'

0 commit comments

Comments
 (0)