1

I draw a graph but unfortunately my legend falls out of the figure. How can I correct it? I put a dummy code to illustrate it: enter image description here

from matplotlib import pyplot as plt
from bisect import bisect_left,bisect_right
import numpy as np
global ranOnce
ranOnce=False
def threeLines(x):
    """Draws a function which is a combination of two lines intersecting in
    a point one with a large slope and one with a 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));
    for i 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)} for a 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()
4

1 回答 1

2

您可以通过修改子图参数来调整一组坐标轴在图中所占的空间。例如,在之前添加以下行plt.show()

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

您应该根据您认为合适的范围调整上述值[0, 1]。随意摆脱您对调整不感兴趣的参数(例如,由于您的图形中只有一个轴,您不会关心hspaceandwspace参数,它会修改子图之间的间距)。这些设置也可以通过plt.show()GUI 修改,但每次运行脚本时都必须这样做。一组适合您的情况的良好设置如下:

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

要自动进行此调整,您可以尝试使用tight_layout(). 在之前添加以下行plt.show()

plt.tight_layout()

但是,这不一定会在每种情况下都给出预期的结果。

于 2013-05-04T00:50:24.923 回答