How to format labels in scientific notation for bar_label

Question:

I am plotting data in a seaborn barplot. I want to label something from my pandas dataframe into the bar. I have gotten the labeling part figured out (see code to replicate below), but I still want to convert it to scientific notation.

import pandas as pd
d = {'name': ['experiment1','experiment2'], 'reads': [15000,12000], 'positiveEvents': [40,60]}
df = pd.DataFrame(d)
df['proportianPositive'] = df['positiveEvents']/df['reads']

p = sns.barplot(data=df,x='name',y='positiveEvents', palette = 'colorblind', alpha =0.8)
p.bar_label(p.containers[0],labels=df.proportianPositive, padding = -50, rotation=90)
plt.show()

Result:

output script above

How do I convert df.proportianPositive to scientific notation so that it will show up on my barplot?

Asked By: Olaf

||

Answers:

That’s probably because the labels argument overrides the fmt argument. Try formatting the labels:

p.bar_label(p.containers[0], padding = -50, rotation=90,
            labels=df.proportianPositive.apply('{:.2e}'.format), 
            )

Output:

enter image description here

Answered By: Quang Hoang
  • As already stated, labels= supersedes fmt=, so they may not be used together.
  • p.containers[0]<BarContainer object of 2 artists>, which are the properties describing the bars.
    • If using the default height (vertical bars), or width (horizontal bars), then use the fmt='%.3E'
    • If using custom labels, the formatting must be applied to the object passed to labels=
  • See How to add value labels on a bar chart for additional details, and examples, using matplotlib.pyplot.bar_label.

fmt=

ax = sns.barplot(data=df, x='name', y='positiveEvents', palette='colorblind', alpha=0.8)
xa.bar_label(ax.containers[0], fmt='%.3E')

enter image description here

labels=

ax = sns.barplot(data=df, x='name', y='positiveEvents', palette='colorblind', alpha=0.8)

labels = df['proportianPositive'].map(lambda v: f'{v:.3E}')  # pandas.Series
# labels = [f'{v:.3E}' for v in df.proportianPositive]  # list comprehension
ax.bar_label(ax.containers[0], labels=labels)

enter image description here

Answered By: Trenton McKinney