2014-05-22 2 views
1

전설과 텍스트 상자 위치와 스타일을 정확히 동일하게 설정하고 싶습니다. 특히 후자는 텍스트를 정렬하는 것이 좋습니다.범례 텍스트와 결합하여 전설의 폭과 높이를 찾는 방법

import matplotlib.pyplot as plt 

x = np.arange(10) 
fig = plt.figure() 
ax = fig.add_subplot(1, 1, 1) 
for i in range(3): 
    ax.plot(x, i * x ** 2, label = '$y = %i x^2$'%i) 
ax.set_title('example plot') 

# Shrink the axis by 20% to put legend and text at the bottom 
#+ of the figure 
vspace = .2 
box = ax.get_position() 
ax.set_position([box.x0, box.y0 + box.height * vspace, 
box.width, box.height * (1 - vspace)]) 

# Put a legend to the bottom left of the current axis 
x, y = 0, 0 
# First solution 
leg = ax.legend(loc = 'lower left', bbox_to_anchor = (x, y), \ 
bbox_transform = plt.gcf().transFigure) 

# Second solution 
#leg = ax.legend(loc = (x, y)) , bbox_transform = plt.gcf().transFigure) 

# getting the legend location and size properties using a code line I found 
#+ somewhere in SoF 
bb = leg.legendPatch.get_bbox().inverse_transformed(ax.transAxes) 

ax.text(x + bb.width, y, 'some text', transform = plt.gcf().transFigure, \ 
bbox = dict(boxstyle = 'square', ec = (0, 0, 0), fc = (1, 1, 1))) 
plt.show() 

이 텍스트는 범례 상자 오른쪽에 텍스트를 배치해야하지만 실제로는 그렇지 않습니다. 그리고 두 상자는 수직으로 정렬되어 있지 않습니다. 두 번째 해결 방법은 실제로 범례를 그림에 고정하는 것이 아니라 축에 고정하는 것입니다.

답변

0

Text() 개체를 올바르게 배치하기 위해 프레임 데이터를 사용하여 올바른 너비를 얻을 수 있습니다.

아래 예제에서 나는 너비에 대해 1.1 요소를 적용해야했습니다.이 값은 얻는 방법을 찾지 못했고 요인을 적용하지 않으면 범례와 충돌합니다.

오른쪽 너비 값을 가져 오기 전에 plt.draw()을 입력해야합니다. x, y = 0.2, 0.5에 대한

import matplotlib.pyplot as plt 
import numpy as np 

x = np.arange(10) 
fig = plt.figure(figsize=(3, 2)) 
ax = fig.add_subplot(1, 1, 1) 
for i in range(3): 
    ax.plot(x, i*x**2, label=r'$y = %i \cdot x^2$'%i) 
ax.set_title('example plot') 
ax.spines['top'].set_visible(False) 
ax.spines['right'].set_visible(False) 
ax.xaxis.set_ticks_position('bottom') 
ax.yaxis.set_ticks_position('left') 

x, y = 0.2, 0.5 
leg = ax.legend(loc='lower left', bbox_to_anchor=(x, y), 
       bbox_transform=fig.transFigure, fontsize=8) 
plt.draw() 
f = leg.get_frame() 
w0, h0 = f.get_width(), f.get_height() 
inv = fig.transFigure.inverted() 
w, h = inv.transform((w0, h0)) 

ax.text(x+w*1.1, y+h/2., 'some text', transform=fig.transFigure, 
     bbox=dict(boxstyle='square', ec=(0, 0, 0), fc=(1, 1, 1)), 
     fontsize=7) 

fig.savefig('test.jpg', bbox_inches='tight') 

: enter image description here

x, y = -0.3, -0.3에 대한 :

enter image description here

+0

나는 같은 결과를받지 못했습니다. matplotlib 1.1.1을 사용하고 있습니다. 어느 것이 너 니? f, w0, h0, inv, w, h의 값을 넣을 수 있습니까? 또한 figsize = (3, 2)를 사용하지 않고 동일한 결과를 얻으실 수 있습니까? – user1850133

+0

@ user1850133 matplotlib 1.3.1을 사용하고 있습니다.이 대화를 [이 방]에서 계속하십시오 (http://chat.stackoverflow.com/rooms/52731/discussion-between-saullo-castro-and-tcapelle) –

+0

@ user1850133 이 대답이 당신에게 효과가 있습니까? –

관련 문제