2016-02-25 149 views
2

enter image description here enter image description here意外覆蓋

它看起來像在第一張圖中的數據點意外覆蓋第二圖。我正在運行的代碼正在運行幾次,當我第一次運行它時,第二次運行它時,我有更長的時間段,而短時間內的數據點也是更長時間段的一部分。

那麼在開始構建圖形之前有什麼方法可以清理繪圖嗎?

你可以看到代碼在這裏構建圖:

def create_graph(self, device): 

    # 800 and 355 pixels. 
    ticks = 5 
    width = 8 
    height = 3.55 

    dpi = 100 
    bgcolor = '#f3f6f6' 

    font = { 
     'size': 16, 
     'family': 'Arial' 
    } 
    plt.rc('font', **font) 

    # size of figure and setting background color 
    fig = plt.gcf() 
    fig.set_size_inches(width, height) 
    fig.set_facecolor(bgcolor) 

    # axis color, no ticks and bottom line in grey color. 
    ax = plt.axes(axisbg=bgcolor, frameon=True) 
    ax.xaxis.set_ticks_position('none') 
    ax.spines['bottom'].set_color('#aabcc2') 
    ax.yaxis.set_ticks_position('none') 

    # removing all but bottom spines 
    for key, sp in ax.spines.items(): 
     if key != 'bottom': 
      sp.set_visible(False) 

    # setting amounts of ticks on y axis 
    yloc = plt.MaxNLocator(ticks) 
    ax.yaxis.set_major_locator(yloc) 


    x_no_ticks = 8 
    # Deciding how many ticks we want on the graph 
    locator = AutoDateLocator(maxticks=x_no_ticks) 
    formatter = AutoDateFormatter(locator) 
    # Formatter always chooses the most granular since we have granular dates 
    # either change format or round dates depending on how granular 
    # we want them to be for different date ranges. 
    formatter.scaled[1/(24.*60.)] = '%d/%m %H:%M' 

    ax.xaxis.set_major_locator(locator) 
    ax.xaxis.set_major_formatter(formatter) 

    # turns off small ticks 
    plt.tick_params(axis='x', 
        which='both', 
        bottom='on', 
        top='off', 
        pad=10) 
    # Can't seem to set label color differently, changing tick_params color changes labels. 
    ax.xaxis.label.set_color('#FFFFFF') 

    # setting dates in x-axis automatically triggers use of AutoDateLocator 
    x = [datetime.fromtimestamp(point['x']) for point in device['data']] 
    y = [point['y'] for point in device['data']] 
    plt.plot(x, y, color='#53b4d4', linewidth=2) 

    # pick values for y-axis 
    y_ticks_values = np.array([point['y'] for point in device['data']]) 
    y_ticks = np.linspace(y_ticks_values.min(), y_ticks_values.max(), ticks) 
    y_ticks = np.round(y_ticks, decimals=2) 
    plt.yticks(y_ticks, [str(val) + self.extract_unit(device) for val in y_ticks]) 
    # plt.ylim(ymin=0.1) # Only show values of a certain threshold. 

    plt.tight_layout() 
    buf = io.BytesIO() 
    plt.savefig(buf, 
       format='png', 
       facecolor=fig.get_facecolor(), 
       dpi=dpi) 
+0

而不是'fig = plt.gcf()',不會'fig = plt.figure()'解決你的問題?與'plt.savefig'(...)之後的'plt.close()'一起? – jrjc

+0

plt.close()解決了我的問題。你可以繼續添加,作爲回答:) – Jonathan

回答

1

你必須plt.savefig()後添加plt.close()。所以這個數字不會被下一個plt.gcf()呼叫所捕獲。