【问题标题】:matplotlib text annotation horizontalmatplotlib 文本注释水平
【发布时间】:2020-08-10 23:59:47
【问题描述】:

我有以下图表:

我想将每个条注释如下:

条形图的代码如下:

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 注释所有条形图,并且位置不在条形图内。

关于如何解决这个问题的任何想法?

【问题讨论】:

标签: python python-3.x matplotlib


【解决方案1】:

这是一个使用修改版答案的示例: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. 

结果:

【讨论】:

    猜你喜欢
    • 2016-10-13
    • 1970-01-01
    • 2020-03-31
    • 2018-05-15
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    • 2020-01-08
    相关资源
    最近更新 更多