2013-04-20 6 views
12

텍스트를 같은 애스펙트 그림의 오른쪽 하단 모서리에 배치하고 싶습니다. ax.transAxes, 으로 그림을 기준으로 위치를 설정했지만 각 그림의 높이 배율에 따라 상대 좌표 값을 수동으로 정의해야합니다.Python/Matplotlib - 같은 종횡비 그림의 모서리에 텍스트를 삽입하는 방법

스크립트 내에서 축 높이 스케일과 올바른 텍스트 위치를 파악하는 좋은 방법은 무엇입니까?

ax = plt.subplot(2,1,1) 
ax.plot([1,2,3],[1,2,3]) 
ax.set_aspect('equal') 
ax.text(1,-0.15, 'text', transform=ax.transAxes, ha='right', fontsize=16) 
print ax.get_position().height 

ax = plt.subplot(2,1,2) 
ax.plot([10,20,30],[1,2,3]) 
ax.set_aspect('equal') 
ax.text(1,-0.15, 'text', transform=ax.transAxes, ha='right', fontsize=16) 
print ax.get_position().height            

enter image description here

답변

37

사용 annotate.

사실 난 거의 text을 사용하지 않습니다. 데이터 좌표에 물건을 배치하고 싶을 때도 일반적으로 포인트를 고정 된 거리만큼 오프셋하고 싶습니다. annotate을 사용하면 훨씬 쉽습니다. 당신이 약간 코너에서 오프셋하고 싶은 경우

import matplotlib.pyplot as plt 

fig, axes = plt.subplots(nrows=2, subplot_kw=dict(aspect=1)) 

axes[0].plot(range(1, 4)) 
axes[1].plot(range(10, 40, 10), range(1, 4)) 

for ax in axes: 
    ax.annotate('Test', xy=(1, 0), xycoords='axes fraction', fontsize=16, 
       horizontalalignment='right', verticalalignment='bottom') 
plt.show() 

enter image description here

, 당신이 어떻게 값을 제어 할 수 textcoordsxytext kwarg을 통해 오프셋 (그리고 지정할 수 있습니다 빠른 예를 들어

이 해석됩니다. 오프셋이 축 아래에 배치하려는 경우

import matplotlib.pyplot as plt 

fig, axes = plt.subplots(nrows=2, subplot_kw=dict(aspect=1)) 

axes[0].plot(range(1, 4)) 
axes[1].plot(range(10, 40, 10), range(1, 4)) 

for ax in axes: 
    ax.annotate('Test', xy=(1, 0), xycoords='axes fraction', fontsize=16, 
       xytext=(-5, 5), textcoords='offset points', 
       ha='right', va='bottom') 
plt.show() 

enter image description here

, 당신이 사용할 수있는 그것을 세트를 배치 할 : 나는 여기 horizontalalignmentverticalalignmenthava 약어를 사용하고 있습니다 포인트 아래 거리 :

import matplotlib.pyplot as plt 

fig, axes = plt.subplots(nrows=2, subplot_kw=dict(aspect=1)) 

axes[0].plot(range(1, 4)) 
axes[1].plot(range(10, 40, 10), range(1, 4)) 

for ax in axes: 
    ax.annotate('Test', xy=(1, 0), xycoords='axes fraction', fontsize=16, 
       xytext=(0, -15), textcoords='offset points', 
       ha='right', va='top') 
plt.show() 

enter image description here

또한 자세한 내용은 Matplotlib annotation guide을 참조하십시오.

+0

좋은 답변과 예입니다. 텍스트 대신 주석을 사용하려고합니다. 고맙습니다. – Tetsuro

+0

좋은 답변입니다! 고마워! – HyperCube

관련 문제