2016-09-19 40 views
0

我想在matplotlib中对齐我的文本。下面的代码工作得很好:为什么使用matplotlib文本对齐与字符串格式函数工作不正确?

colors = ['red', 'blue', 'green', 'yellow'] 
for color in colors: 
    print('{:>15}'.format(color)) 

输出:

 red 
     blue 
     green 
    yellow 

然而,相同的字符串格式不plt.text职能的工作:

fig, ax = plt.subplots() 
bar_band = ax.barh(range(len(colors)), np.ones(len(colors)), height=1) 
for i in range(len(colors)): 
    bar_band[i].set_color(colors[i]) 
    ax.text(0.1, i+0.4, "{:>15}".format(colors[i])) 

ax.set_axis_off() 
plt.show() 

我得到的文本对齐而不是中心。谁可以帮我这个事?

enter image description here

+0

,你可以在ax.text(的文档字符串查找),也有称为'horizo​​ntalalignment'可选参数和'verticalalignment',可以做这个工作 – dnalow

+0

http://matplotlib.org/examples/pylab_examples/alignment_test.html – dnalow

回答

0

ax.text()创建matplotlib Text对象,它可以选择horizontalalignment(或ha的简称)。这可以帮助您将文本对齐到您想要的位置。

接受选项'left''right''center'

所以,你可以尝试:

ax.text(0.1, i+0.4, "{:>15}".format(colors[i]), ha='right')