簡體   English   中英

MatPlotLib 文本位置奇怪的行為

[英]MatPlotLib text position strange behavior

我有一個顯示散點圖的功能:

def critics_and_users_score_corr_with_total_sales(_df, platform):
    critic_score_not_na = df['critic_score'].notna() & (df['platform'] == platform)
    total_sales_for_critic_score = df[critic_score_not_na]['total_sales']
    critic_score = df[critic_score_not_na]['critic_score']

    user_score_not_na = df['user_score'].notna() & (df['platform'] == platform)
    total_sales_for_user_score = df[user_score_not_na]['total_sales']
    user_score = df[user_score_not_na]['user_score']

    info_bbox_props = dict(boxstyle='round', facecolor='white', alpha=0.2)

    fig = plt.figure(figsize=(16, 7))
    ax1 = fig.add_subplot(121)
    ax2 = fig.add_subplot(122)

    ax1.grid(True)
    ax1.set_xlim(0,25)
    ax1.set_title('{} Critics score & Total sales correlation'.format(platform))
    ax1.set_xlabel('Total sales')
    ax1.set_ylabel('Critics score')
    ax1.scatter(total_sales_for_critic_score, critic_score, s = 10)

    ax1.text(0.345, 0.88, 'Corelation: {:.2f}'.format(total_sales_for_critic_score.corr(critic_score)), 
             transform=ax.transAxes, verticalalignment='top', horizontalalignment='right', bbox=info_bbox_props)

    ax2.grid(True)
    ax2.set_xlim(0,25)
    ax2.set_title('{} Users score & Total sales correlation'.format(platform))
    ax2.set_xlabel('Total sales')
    ax2.set_ylabel('Users score')
    ax2.scatter(total_sales_for_user_score, user_score, s = 10)
    ax2.text(0.892, 0.88, 'Corelation: {:.2f}'.format(total_sales_for_user_score.corr(user_score)), 
             transform=ax.transAxes, verticalalignment='top', horizontalalignment='right', bbox=info_bbox_props)

    plt.show()

我在代碼中進一步調用了這個函數:

critics_and_users_score_corr_with_total_sales(df, top_platforms.index[0])

結果如下: 在此處輸入圖片說明 正如我們所看到的,文本字段放置在繪圖之外。

但是,如果我通過Shift+Enter第二次和后續時間運行此單元格 - 文本字段將放置在其他位置: 在此處輸入圖片說明

如果我重新啟動內核並運行所有單元格,文本字段將再次放置在繪圖之外。

這是什么魔法?

問題出在以下幾行:

ax1.text(0.345, 0.88, 'Corelation: {:.2f}'.format(total_sales_for_critic_score.corr(critic_score)), 
         transform=ax.transAxes, verticalalignment='top', horizontalalignment='right', bbox=info_bbox_props)

我的 ax 有一個ax1名稱,但我發送到參數transform=ax.transAxes 顯然, ax是在其他地方聲明的。

我的錯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM