2013-04-08 3 views
7

가변 길이의 눈금 레이블이 있으며이를 왼쪽으로 정렬합니다 (즉, 길이가 짧은 것과 y 축 사이에 공백이 있음). 이 일을하는 합리적인 방법이 있습니까? 수평 정렬 '왼쪽'을 사용하면 왼쪽에 정렬되지만, 모두 축에서 시작하여 음모 안에 들어갑니다. 대안적인 질문이있을 수 있습니다 - 출발점을 변경할 수 있습니까? 데모에 대한Matplotlib : y- 틱을 왼쪽으로 정렬

코드 :

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

하나를 사용할 수있는 예제 코드를! – tacaswell

답변

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

+0

@TalKremerman 나는 (단지 mpl의 관점에서) 'just'이라고 주장 할 것이다. 당신은 시작 지점을 변경하는 방법을 물었습니다. 시작 지점이 무엇인지 구분할 방법이 아닙니다.) – tacaswell

+0

멋진 예제. 다른 목적으로도 나에게 매우 유용 할 것이다. 감사합니다 – Korem

관련 문제