colla
colla

Reputation: 847

matplotlib text annotation horizontal

I have the following graph: actual output

And I would like to annotate each bar as follow : wanted output

The code for the bar graph is the following :

xs = sumAgent['Year'].values
ys = sumAgent['agentCom'].values
plt.barh(xs,ys)

I have a list of strings : lst = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']

I would like to annotate my bars with the following strings (first element of the list = annotation of first bar).

for x,y in zip(xs,ys):

label = "{:.2f}".format(y)

plt.annotate('A', # this is the text
             (x,y), # this is the point to label
             textcoords="offset points", # how to position the text
             xytext=(0,10), # distance from text to points (x,y)
             ha='center') # horizontal alignment can be left, right or center

But of course it will annotate all bars with value A and the position is not inside the bar graph.

Any ideas on how I could resolve this ?

Upvotes: 2

Views: 973

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169494

Here's an example using a modified version of the answer here: https://stackoverflow.com/a/51410758/42346

df = pd.DataFrame({'a':[10,50,100,150,200,300],'b':[5,10,30,50,200,250]})
rects = plt.barh(df['a'].values,df['b'].values,height=13)

for rect in rects:  
     x_value = rect.get_width() 
     y_value = rect.get_y() + rect.get_height() / 2 

     # Number of points between bar and label. Change to your liking.
     space = -1 
     ha = 'right' 

     # If value of bar is low: Place label right of bar 
     if x_value < 20: 
         # Invert space to place label to the right 
         space *= -1  
         ha = 'left'   

     # Use X value as label and format number with no decimal places 
     label = "{:.0f}".format(x_value) 

     # Create annotation 
     plt.annotate( 
         label,                      # Use `label` as label 
         (x_value+space, y_value),         # Place label at end of the bar 
         xytext=(space, 0),          # Horizontally shift label by `space` 
         textcoords="offset points", # Interpret `xytext` as offset in points 
         va='center',                # Vertically center label 
         ha=ha)                      # Horizontally align label differently. 

Result: enter image description here

Upvotes: 1

Related Questions