Python matplotlib文本注释水平
我有以下图表: 我想对每个条进行如下注释: 条形图的代码如下所示:Python matplotlib文本注释水平,python,python-3.x,matplotlib,Python,Python 3.x,Matplotlib,我有以下图表: 我想对每个条进行如下注释: 条形图的代码如下所示: xs = sumAgent['Year'].values ys = sumAgent['agentCom'].values plt.barh(xs,ys) 我有一个字符串列表: lst=['A','B','C','D','E','F','G','H','I','J'] 我想用以下字符串注释我的条形图(列表的第一个元素=第一条条形图的注释) 但当然,它将用值A注释所有条形图,并且位置不在条形图内 有没有办法解决这个问题 下面是一
xs = sumAgent['Year'].values
ys = sumAgent['agentCom'].values
plt.barh(xs,ys)
我有一个字符串列表:
lst=['A','B','C','D','E','F','G','H','I','J']
我想用以下字符串注释我的条形图(列表的第一个元素=第一条条形图的注释)
但当然,它将用值A注释所有条形图,并且位置不在条形图内
有没有办法解决这个问题 下面是一个使用修改版答案的示例:
df=pd.DataFrame({'a':[10,50100150200300],'b':[5,10,30,50200250]})
矩形=plt.barh(df['a']值,df['b']值,高度=13)
对于矩形中的矩形:
x_值=rect.get_宽度()
y_值=rect.get_y()+rect.get_height()/2
#条和标签之间的点数。改变你的喜好。
空格=-1
哈=‘对’
#如果条形图的值较低:将标签放置在条形图的右侧
如果x_值<20:
#反转空间以将标签放置到右侧
空格*=-1
ha=‘左’
#使用X值作为标签,并设置无小数点的数字格式
label=“{.0f}”。格式(x_值)
#创建注释
附注(
标签,#使用'label'作为标签
(x_值+空格,y_值),#将标签放在条的末尾
xytext=(空格,0),#按“空格”水平移动标签
textcoords=“偏移点”,#将'xytext'解释为点中的偏移
va='center',#垂直居中标签
ha=ha)#以不同方式水平对齐标签。
结果:
谢谢您,但是如何将标签放置在水平条内?您是否在寻找此标签的变体
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
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.