python - How to make matplotlib show legend which falls out of figure? -


i draw graph unfortunately legend falls out of figure. how can correct it? put dummy code illustrate it: enter image description here

from matplotlib import pyplot plt bisect import bisect_left,bisect_right import numpy np global ranonce ranonce=false def threelines(x):     """draws function combination of 2 lines intersecting in     point 1 large slope , 1 small slope.     """     start=0     mid=5     end=20     global ranonce,slopes,intervals,intercepts;     if(not ranonce):         slopes=np.array([5,0.2,1]);         intervals=[start,mid,end]         intercepts=[start,(mid-start)*slopes[0]+start,(end-mid)*slopes[1]+(mid-start)*slopes[0]+start]         ranonce=true;     place=bisect_left(intervals,x)     if place==0:         y=(x-intervals[place])*slopes[place]+intercepts[place];     else:             y=(x-intervals[place-1])*slopes[place-1]+intercepts[place-1];     return y; def threelinesdrawer(minimum,maximum):     t=np.arange(minimum,maximum,1)     fig=plt.subplot(111)     markersize=400;     fig.scatter([minimum,maximum],[threelines(minimum),threelines(maximum)],marker='+',s=markersize)      y=np.zeros(len(t));     in range(len(t)):         y[i]=int(threelines(t[i]))     fig.scatter(t,y)     fig.grid(true)     fig.set_xlabel('y')     fig.set_ylabel('x')     legend1 = plt.circle((0, 0), 1, fc="r")     legend2 = plt.circle((0, 0), 1, fc="b")     legend3 = plt.circle((0, 0), 1, fc="g")     fig.legend([legend1,legend2,legend3], ["p(y|x) likelihood","max{p(y|x)} specific x","y distribution"],     bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=2, mode="expand", borderaxespad=0.)  threelinesdrawer(0,20) plt.show() 

you can adjust space set of axes takes within figure modifying subplot parameters. example, add following line before plt.show():

plt.subplots_adjust(top=.9, bottom=.1, hspace=.1, left=.1, right=.9, wspace=.1) 

you should tweak above values see fit in range of [0, 1]. feel free rid of parameters you're not interested in tweaking (e.g. since have 1 axis in figure, won't care hspace , wspace parameters, modify spacing between subplots). these settings can modified through plt.show() gui, you'd have every time run script. set of settings case following:

plt.subplots_adjust(top=.83, bottom=.08, left=.08, right=.98) 

for doing adjustment automatically, can try using tight_layout(). add following line before plt.show():

plt.tight_layout() 

this won't give intended results in every case, though.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

java - Are there any classes that implement javax.persistence.Parameter<T>? -