2017-10-25 13 views
1

私は、高さが軸の高さよりも大きい凡例(下のコードの結果のような)を持つプロットを持っています。今、私は軸の高さを伝説の終わりで終わるように伸ばしたいと思います。私が持っていると思いますがそのような何か(グリッドの底部またはダニの底が伝説で終わる場合、それは、問題ではありません)軸の高さを設定する - 凡例の高さに軸を伸ばします

enter image description hereある

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

私は(legend_hは常に= 1.0である)を追加次のコードではなく任意の影響を受けずに自分の目標を達成しようとした:

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()) 

さらに、軸全体のプロパティではなく、軸自体のプロパティのみを変更できるといいですね。

編集: 私の主な目的は、スクリプトからフィギュアの生成を実行することですが、私はまた、Ipythonノートでそれを試してみました。 1つの試みは、高さを取得して新しいFigureの高さを設定する前に、Figureを一時的に格納することでした。しかし、それは正しい結果をもたらさなかった。

答えて

0

私はあなたが既に持っているものにplt.draw()を追加するだけで、あなたが望むものを達成できると思います。

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ノートブックで動作していますが、スクリプトでは動作していません。 – AnnetteC

+0

最後に 'fig.tight_layout()'を追加しようとしました。(これは凡例をちょっと傷つけることがあります) –

+0

は動作しません。 – AnnetteC

0

、@Mattピトキンの答えは正しいアプローチを示しています。しかし、set_figheightではなくset_size_inchesを使用します。計算には数字マージンも含める必要があります。これはfig.subplotparsから取得できます。

さらに、高さに加えて、凡例が含まれるようにFigureの幅を設定することもできます。

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() 

以下の図は、これをスクリプトとして実行しているときの画像です。 Ipython又はjupyterで

enter image description here

示すPNGが自動的bbox_inches='tight'オプションを使用して保存されているので、図は、自動的に、トリミング又は拡大されます。したがって、ジュピターノートブックでは幅調整は必要ありません。

関連する問題