0
STRUD Struct_Count Perc
Row 1151 38.37
Single 865 28.83
Detached 447 14.90
Row End 384 12.80
Multi 146 4.87
Inside 3 0.10
Missing 2 0.07
Default 1 0.03
Town End 1 0.03
plt.figure(figsize=(15, 8))
 
plots = sns.barplot(x="STRUD", y="Struct_Count", data=df2)
 
for bar in plots.patches:  
 
    # Using Matplotlib's annotate function and
    # passing the coordinates where the annotation shall be done
    plots.annotate(format(bar.get_height(), '.0f'),
                   (bar.get_x() + bar.get_width() / 2,
                    bar.get_height()), ha='center', va='center',
                   size=13, xytext=(0, 5),
                   textcoords='offset points')
    
plt.title("Distribution of STRUCT")
 
plt.show()

With the above code learnt from the forum, I am able to plot the 'struct_count' values, how can I plot the corresponding percentage values on the bars. Thanks for the help in advance.

PDitta
  • 19
  • 6

1 Answers1

2

You can play around with the ax.bar_label in order to set custom labels. No need for annotations and loops.

I'm assuming the below example is what you mean by "plot the corresponding percentage values on the bars", but it can be adjusted flexibly.

Note that this doesn't show values smaller than 1%, since those would be overlapping the x-axis and the other label. This can also be easily adjusted below.

The docs have some instructive examples.

import seaborn as sns
import matplotlib.pyplot as plt

fig, ax = plt.subplots(1, 1, figsize=(15, 8))
plots = sns.barplot(x="STRUD", y="Struct_Count", data=df2, ax=ax)
ax.bar_label(ax.containers[0])
ax.bar_label(ax.containers[0], 
             labels=[f'{e}%' if e > 1 else "" for e in df2.Perc],
             label_type="center")
plt.title("Distribution of STRUCT")

enter image description here

mcsoini
  • 6,280
  • 2
  • 15
  • 38
  • thanks a lot, it helps.. I tried to below to get xy cordinates, height and width properties of the bars.. is there a way we can use these to display all the perc labels ? for bar in ax.patches: #ax.annotate() height = bar.get_height() width = bar.get_width() print(height,width) x = bar.get_x() y = bar.get_y() print(x,y) print(plt.xlim(),plt.ylim()) for i,v in enumerate(ax.containers[0]): print (i,v) – PDitta Jun 04 '22 at 10:44