Home > Mobile >  How do I add a string to seaborn bar_label?
How do I add a string to seaborn bar_label?

Time:03-30

I need to display the data above a seaborn barplot. The numbers represent dollars and I would like to display the value 25200 as $25.2k.

This is the code I currently use to display the below graph.

import seaborn as sns
import matplotlib.pyplot as plt

i = sns.barplot(ax = axes[1,0], x=lr_2021['decile'], y=np.round((lr_2021['NonCAT Severity']/1000),2), color = 'purple')
i.bar_label(axes[1,0].containers[0])

Which displays this:

enter image description here

I tried adding the following to the bar_label line:

i.bar_label(axes[1,0].containers["$",0, "K"])

That error'd out however. Is this possible?

CodePudding user response:

If you only need to add a $ prefix and K suffix, the fmt param is simplest:

i.bar_label(axes[1,0].containers[0], fmt='$%gK')

But in this case, you also need to divide the values by 1000. That's too complex for fmt, so instead apply an f-string to the container's datavalues via the labels param:

bars = axes[1,0].containers[0]
i.bar_label(bars, labels=[f'${value/1000:.1f}K' for value in bars.datavalues])
  • Related