Skip to content

Commit d11e53d

Browse files
committed
Add callable as option for fmt.
1 parent 6db8509 commit d11e53d

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

lib/matplotlib/axes/_axes.py

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2622,8 +2622,9 @@ def bar_label(self, container, labels=None, *, fmt="%g", label_type="edge",
26222622
A list of label texts, that should be displayed. If not given, the
26232623
label texts will be the data values formatted with *fmt*.
26242624
2625-
fmt : str, default: '%g'
2626-
A format string for the label.
2625+
fmt : str or callable, default: '%g'
2626+
A format string for the label or a function to call with the value
2627+
as the first argument.
26272628
26282629
label_type : {'edge', 'center'}, default: 'edge'
26292630
The label type. Possible values:
@@ -2746,9 +2747,18 @@ def sign(x):
27462747
lbl = ''
27472748

27482749
if lbl is None:
2749-
formatted_value = (
2750-
fmt.format(value) if fmt.startswith('{') else fmt % value
2751-
)
2750+
if callable(fmt):
2751+
formatted_value = fmt(value)
2752+
elif isinstance(fmt, str):
2753+
if fmt.count('{:') == fmt.count('}') == 1:
2754+
formatted_value = fmt.format(value)
2755+
else:
2756+
formatted_value = fmt % value
2757+
else:
2758+
raise ValueError(
2759+
'fmt expected to be a callable or a format string. '
2760+
f'Got "{fmt}".'
2761+
)
27522762
else:
27532763
formatted_value = lbl
27542764
annotation = self.annotate(formatted_value,

0 commit comments

Comments
 (0)