2017-07-11 51 views
1

當我運行該功能,爲什麼兩個數字對象出現而不是一個?

def plot_data(df, title="", xlabel="", ylabel="", figsize=(12, 8), save_figure=False): 
    from matplotlib.font_manager import FontProperties 
    fontP = FontProperties() 
    fontP.set_size('small') 
    plt.xlabel(xlabel) 
    plt.ylabel(ylabel) 

    plt.legend(bbox_to_anchor=(1,1), loc='upper left', prop=fontP) 
    plt.grid() 

    df.plot() 
    plt.show() 

    if save_figure: 
     plt.savefig(title) 

的結果是這樣的:

enter image description here

我不明白爲什麼是兩個圖形對象上來。它看起來像legend,grid沒有適當適用...

此外,我想清楚地知道「圖形對象創建時」或「我怎樣才能創建一個沒有混淆的圖形對象」的東西。有沒有什麼好的教程?

+0

我覺得最後一段有點太廣,特別是如果你混合'matplotlib'和' pandas'。有一些matplotlib教程(即https://matplotlib.org/users/pyplot_tutorial.html#working-with-multiple-figures-and-axes是一個很好的起點),但它們與'pandas'直接相關的方式更多複雜。 – MSeifert

回答

3

這是因爲DataFrame.plot默認情況下不使用當前活動數字,而是創建一個新數字。但是,這只是默認行爲 - 你可以通過明確地傳遞主動軸(ax參數)在其覆蓋:

df.plot(ax=plt.gca()) # gca stands for "get currently axes" instance 

或者你可以簡單地在頂部放命令,因爲(不像)最plt功能修改當前活躍的身影,有的plt命令(例如legend),即使不會,如果沒有「陰謀」,但工作:

def plot_data(df, title="", xlabel="", ylabel="", figsize=(12, 8), save_figure=False): 

    # Moved to the top 
    df.plot() 

    from matplotlib.font_manager import FontProperties 
    fontP = FontProperties() 
    fontP.set_size('small') 
    plt.xlabel(xlabel) 
    plt.ylabel(ylabel) 

    plt.legend(bbox_to_anchor=(1,1), loc='upper left', prop=fontP) 
    plt.grid() 

    plt.show() 

    if save_figure: 
     plt.savefig(title) 
相關問題