2013-05-03 34 views
1

我畫了一張圖,但不幸的是我的傳奇脫離了這個數字。我該如何糾正它? 我把一個僞代碼來說明它: enter image description here如何讓matplotlib展示掉身材的傳奇?

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

回答

2

可以調整空間一組軸,通過修改參數次要情節發生的圖之內。例如,剛剛plt.show()之前添加以下行:

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

,你在[0, 1]範圍內認爲合適的時候應該調整上述值。隨意擺脫你不感興趣調整的參數(例如,因爲你的圖中只有一個軸,你不會在乎hspacewspace參數,這些參數修改了子圖之間的間距)。這些設置也可以通過plt.show() GUI進行修改,但每次運行腳本時都必須執行此操作。一組爲您好的情況下設置如下:

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

自動做這樣的調整,你可以嘗試使用tight_layout()。只是plt.show()之前添加以下行:

plt.tight_layout() 

這不一定會放棄在任何情況下預期的結果,雖然。