matplotlib文本注释水平

2024-09-29 19:36:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的图表: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注释所有条形图,并且位置不在条形图内

有没有办法解决这个问题


Tags: theto字符串text列表ispltthis
1条回答
网友
1楼 · 发布于 2024-09-29 19:36:24

这里有一个例子,使用了这里答案的修改版本: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. 

结果: enter image description here

相关问题 更多 >

    热门问题