【问题标题】:MatPlotLib text position strange behaviorMatPlotLib 文本位置奇怪的行为
【发布时间】:2020-05-05 17:16:54
【问题描述】:

我有一个显示散点图的功能:

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 运行此单元格 - 文本字段将放置在其他位置:

如果我重新启动内核并运行所有单元格,文本字段将再次放置在绘图之外。

这是什么魔法?

【问题讨论】:

标签: python pandas matplotlib jupyter-notebook


【解决方案1】:

问题出在以下几行:

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)

我的斧头有一个ax1 名称,但我发送到参数transform=ax.transAxes。显然,ax 是在其他地方声明的。

我的错。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    相关资源
    最近更新 更多