горизонтальная текстовая аннотация matplotlib - PullRequest
2 голосов
/ 27 апреля 2020

У меня есть следующий график: actual output

И я хотел бы аннотировать каждый столбец следующим образом: wanted output

Код для гистограммы следующий:

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

У меня есть список строк: lst = ['A', 'B', 'C', 'D', 'E' , 'F', 'G', 'H', 'I', 'J']

Я хотел бы аннотировать мои бары следующими строками (первый элемент списка = аннотация первого бара) ,

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

Но, конечно, он будет аннотировать все бары со значением A, и позиция не будет находиться внутри гистограммы.

Есть идеи, как мне решить эту проблему?

1 Ответ

1 голос
/ 27 апреля 2020

Вот пример использования модифицированной версии ответа: { ссылка }

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. 

Результат: enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...