Issue
I have been using the ax.bar_label
method to add data values to the bar graphs. The numbers are huge such as 143858918. How can I add commas to the data values using the ax.bar_label
method? I do know how to add commas using the annotate method but if it is possible using bar_label
, I am not sure. Is it possible using the fmt
keyword argument that is available?
Solution
fmt
still uses the old%
operator (as of 3.5.1), which doesn't support comma separators (as far as I know).- Instead, use the
labels
param with f-strings.
Get the heights of the container patches and format them with {:,}
to get comma separators:
container = ax.containers[0]
ax.bar_label(container, labels=[f'{p.get_height():,}' for p in container])
Or for grouped bar charts, iterate all the containers:
for container in ax.containers:
ax.bar_label(container, labels=[f'{p.get_height():,}' for p in container])
Toy example:
x = np.random.default_rng(123).integers(10_000_000, size=5)
fig, ax = plt.subplots()
ax.bar(range(len(x)), x)
container = ax.containers[0]
ax.bar_label(container, labels=[f'{p.get_height():,}' for p in container])
Answered By - tdy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.