How To Add Data Labels To Seaborn Barplot?
I have the following code to produce a bar plot in seaborn import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df = pd.DataFrame(np.random.randint(0,100,size
Solution 1:
As of matplotlib 3.4.0, you can replace the annotation loop with the built-in Axes.bar_label
.
In your code, chart
is an Axes
object, so you can just use:
chart.bar_label(chart.containers[0])
Note that a grouped bar chart (with hue
) would have multiple bar containers
, so in that case containers
would need to be iterated:
for container in chart.containers:
chart.bar_label(container)
Solution 2:
For those intersted in how I solved it:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
print(df):
A B C D
0311165151832158721668141391789570426512661
.. .. .. .. ..
9531189124967397424597762223698124398279933966768
probbins = [0,10,20,30,40,50,60,70,80,90,100]
df['Groups'] = pd.cut(df['D'],bins=probbins)
plt.figure(figsize=(15,6))
chart = sns.barplot(x=df['Groups'], y=df['C'],estimator=sum,ci=None)
chart.set_title('Profit/Loss')
chart.set_xticklabels(chart.get_xticklabels(), rotation=30)
# annotation herefor p in chart.patches:
chart.annotate("%.0f" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()),
ha='center', va='center', fontsize=10, color='black', xytext=(0, 5),
textcoords='offset points')
plt.show()
Post a Comment for "How To Add Data Labels To Seaborn Barplot?"