2013-04-08 122 views
7

我有可變長度的tick標籤,並且我想將它們對齊到左邊(即在較短和y軸之間有一個空格)。有沒有合理的方法來做到這一點? 使用水平對齊'左'將它們對齊到左側,但它們都從該軸開始,因此它們最終位於該圖的內部。因此,另一個問題可能是 - 我可以改變他們的出發點嗎?Matplotlib:將y-ticks左對齊

代碼演示:

import numpy as np 
import matplotlib.pyplot as plt 

ticks = ["Lorem ipsum dolor sit amet, consectetur adipisicin", "g elit, sed do",  "eiusmod tempor incididunt ut labo", "re et dolore magna ali", "qua. Ut en", "im ad minim veniam, quis nostr", "ud exercitation ullamco labo", "ris nisi ut aliquip ex ea c", "ommodo co", "nsequat. Duis aute irure dolor in rep"] 
data = [5,1,2,4,1,4,5,2,1,5] 
ind = np.arange(len(data)) 
fig = plt.figure() 
ax = plt.subplot(111) 
ax.barh(ind, data, 0.999) 
ax.set_yticks(ind + 0.5) 
r = ax.set_yticklabels(ticks)#, ha = 'left') 
fig.set_size_inches(12, 8) 
fig.savefig(r'C:\try.png', bbox_extra_artists=r, bbox_inches='tight') 
+0

+1的可用示例代碼! – tacaswell 2013-04-08 19:49:32

回答

8

你只需要添加一個pad。見matplotlib ticks position relative to axis

yax = ax.get_yaxis() 
yax.set_tick_params(pad=pad) 

(doc)

做你的墊應該是什麼盤算:

import numpy as np 
import matplotlib.pyplot as plt 

ticks = ["Lorem ipsum dolor sit amet, consectetur adipisicin", "g elit, sed do",      "eiusmod tempor incididunt ut labo", "re et dolore magna ali", "qua. Ut en", "im ad minim veniam, quis nostr", "ud exercitation ullamco labo", "ris nisi ut aliquip ex ea c", "ommodo co", "nsequat. Duis aute irure dolor in rep"] 
data = [5,1,2,4,1,4,5,2,1,5] 
ind = np.arange(len(data)) 
fig = plt.figure(tight_layout=True) # need tight_layout to make everything fit 
ax = plt.subplot(111) 
ax.barh(ind, data, 0.999) 
ax.set_yticks(ind + 0.5) 
r = ax.set_yticklabels(ticks, ha = 'left') 
fig.set_size_inches(12, 8, forward=True) 
# re-size first, the shift needs to be in display units 
plt.draw() # this is needed because get_window_extent needs a renderer to work 
yax = ax.get_yaxis() 
# find the maximum width of the label on the major ticks 
pad = max(T.label.get_window_extent().width for T in yax.majorTicks) 

yax.set_tick_params(pad=pad) 
plt.draw() 

demo of code

+0

感謝您的指針。但它不是「只」:) 爲了這個工作,我需要找出一種方法來獲得最大滴答點的大小...有關此事的任何提示? – Korem 2013-04-08 18:26:55

+0

@TalKremerman我認爲(從mpl的角度來看)它是'正義'。你問如何改變他們的出發點,而不是解決什麼樣的出發點的方法;) – tacaswell 2013-04-08 19:51:42

+0

精彩的例子。對於其他用途我也會非常有用。謝謝 – Korem 2013-04-09 07:21:14