2014-03-26 105 views
5

有沒有辦法讓第三軸顯示的結果只有一個ax.text()命令?使用expandtabs幾乎讓我在那裏,但文字從未正確對齊。Matplotlib文本對齊

使用兩個繪圖命令對我來說似乎不是一個好習慣,你總是需要猜測兩者之間的距離,這可能需要一些迭代。

fig, axs = plt.subplots(1,3, figsize=(12,4), 
         subplot_kw={'aspect': 1, 'xticks': [], 'yticks':[]}) 
fig.subplots_adjust(wspace=0.05) 

values = {'a': 1.35, 'b': 25.1, 'c': 5} 

tmpl = """Param1: {a:1.1f} 
Long param2: {b:1.1f} 
Prm3: {c:1.1f}""" 

mystr = tmpl.format(**values) 
axs[0].text(0.1, 0.9, mystr, va='top', transform=axs[0].transAxes) 
axs[0].set_title('Default') 


tmpl = """Param1:\t\t\t{a:1.1f} 
Long param2:\t{b:1.1f} 
Prm3:\t\t\t{c:1.1f}""".expandtabs() 

mystr = tmpl.format(**values) 
axs[1].text(0.1, 0.9, mystr, va='top', transform=axs[1].transAxes) 
axs[1].set_title('Almost there') 


labels = """Param1: 
Long param2: 
Prm3:""" 

tmpl = """{a:1.1f} 
{b:1.1f} 
{c:1.1f}""" 

mystr = tmpl.format(**values) 
axs[2].text(0.1, 0.9, labels, va='top', transform=axs[2].transAxes) 
axs[2].text(0.65, 0.9, mystr, va='top', ha='right', transform=axs[2].transAxes) 
axs[2].set_title('Target') 

enter image description here

+3

檢查出字符串中的所有格式[這個答案](http://stackoverflow.com/a/9549204/1634191) – wflynny

回答

6

,使得每個字符佔用的空間相同的量使用等寬字體。

import matplotlib.pyplot as plt 

fig, axs = plt.subplots(1,3, figsize=(12,4), 
         subplot_kw={'aspect': 1, 'xticks': [], 'yticks':[]}) 
fig.subplots_adjust(wspace=0.05) 

values = {'a': 1.35, 'b': 25.1, 'c': 5} 

tmpl = """Param1: {a:1.1f} 
Long param2: {b:1.1f} 
Prm3: {c:1.1f}""" 



mystr = tmpl.format(**values) 
axs[0].text(0.1, 0.9, mystr, va='top', transform=axs[0].transAxes) 
axs[0].set_title('Default') 


mono = {'family' : 'monospace'} 

textblock = "1234567890\nabcdefghij\nABCDEFGHIJ\n   0" 

axs[1].text(0.1, 0.9, textblock, va='top', transform=axs[1].transAxes, fontdict=mono) 
axs[1].set_title('Monospaced text block') 


axs[2].text(0.1, 0.9, textblock, va='top', transform=axs[2].transAxes) 
axs[2].set_title('Not monospaced') 

plt.show() 

enter image description here