2017-10-25 1 views
1

높이가 축 높이보다 큰 범례 (예 : 아래 코드 결과)가있는 플롯이 있습니다. 이제 전설이 끝날 때까지 축 높이를 늘리고 싶습니다. 내가하고 싶은 무엇축 높이 설정 - 축 높이를 범례 높이로 늘림

import matplotlib.pyplot as plt 
import numpy as np 

t = np.arange(0., 10.5, 0.5) 

fig, ax = plt.subplots() 
for c in range(0, 20): 
    ax.plot(t, t*c/2, label='func {}'.format(c)) 
ax.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.) 

enter image description here

는 그런 일 (그리드 또는 틱의 바닥의 바닥이 전설로 끝나는 경우는 문제가되지 않습니다)

enter image description here입니다

:

나는 (legend_h 항상 1.0 =입니다) 어떤 효과없이하지만 다음 코드를 추가 내 목표를 달성하기 위해 노력

계속해서 전체 그림이 아닌 축 자체의 속성 만 변경할 수 있다면 좋을 것입니다.

편집 : 내 주요 목적은 스크립트에서 그림 생성을 실행하는 것입니다 그러나 나는 또한 Ipython 노트북에서 그것을 시도했다. 하나의 시도는 또한 높이를 얻고 새로운 그림 높이를 설정하기 전에 그림을 임시로 저장하는 것이 었습니다. 그러나 그것은 또한 정확한 결과를 산출하지 못했습니다.

답변

0

나는 이미 가지고있는 것에을 추가하여 원하는 것을 얻을 수 있다고 생각합니다.

fig, ax = plt.subplots() 
for c in range(0, 20): 
    ax.plot(t, t*c/2, label='func {}'.format(c)) 
ax.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.) 

plt.draw() 

legend_h = ax.get_legend().get_window_extent().height 
ax_height = ax.get_window_extent().height 

if ax_height < legend_h: 
    fig.set_figheight(legend_h/ax_height * fig.get_figheight()) 

업데이트 : 또한, 당신은 (this answer에서 스크립트에서 작업 및 기반해야하는) 시도 할 수는 : 원칙적으로

import matplotlib.pyplot as plt 
import numpy as np 

t = np.arange(0., 10.5, 0.5) 

fig, ax = plt.subplots() 
for c in range(0, 20): 
    ax.plot(t, t*c/2, label='func {}'.format(c)) 
lgd = ax.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.) 

fig.tight_layout() 
fig.savefig('script.png', bbox_extra_artists=(lgd,), bbox_inches='tight') 
+0

예, 지금은 Ipython Notebook에서 작동하지만 스크립트에서는 작동하지 않습니다. – AnnetteC

+0

끝 부분에'fig.tight_layout()'을 추가해보십시오. (이것은 범례를 약간자를 수 있지만) –

+0

이 작동하지 않습니다. – AnnetteC

0

, @ 매트 Pitkin의 대답은 올바른 접근 방식을 보여줍니다. 그러나 set_figheight 대신 set_size_inches을 사용합니다. 또한 계산에는 fig.subplotpars에서 얻을 수있는 그림 여백을 포함시켜야합니다.

또한 높이에 따라 범례가 포함되도록 그림의 너비를 설정할 수도 있습니다.

import matplotlib.pyplot as plt 
import numpy as np 

t = np.linspace(0,10); c=20 

fig, ax = plt.subplots() 
for c in range(0, 20): 
    ax.plot(t, t*c/2, label='func {}'.format(c)) 
bbox = (1.01,1)  
ax.legend(bbox_to_anchor=bbox, loc=2, borderaxespad=0.) 

fig.canvas.draw() 

legend_h = ax.get_legend().get_window_extent().height 
ax_height = ax.get_window_extent().height 
if ax_height < legend_h: 
    w,h = fig.get_size_inches() 
    h =legend_h/fig.dpi/(fig.subplotpars.top-fig.subplotpars.bottom) 
    fig.set_size_inches(w,h) 

# set width as well 
w,h = fig.get_size_inches() 
r = ax.get_legend().get_window_extent().width/fig.dpi/w 
fig.subplots_adjust(right=1-1.1*r) 
plt.show() 

아래 그림은 스크립트로 실행 한 것입니다. 표시된 PNG 자동으로 bbox_inches='tight' 옵션을 사용하여 저장하기 때문에 Ipython 또는 jupyter에서

enter image description here

이 그림은 자동으로 잘립니다 또는 확장됩니다. 따라서 너비 노트북 조정에는 너비 조정이 필요하지 않습니다.