【问题标题】:Python Matplotlib LEGEND customisePython Matplotlib LEGEND 自定义
【发布时间】:2020-08-15 19:25:33
【问题描述】:

有没有办法将图例中红线下方的下方两个指标向左移动? 要么将图例中的红线移动到 0.93 的右侧? 如果做不到这一点,是否有一种快速的方法可以将 R2 与 RMSE 和 MAE 分开,并且有两个不会相互干扰的图例——我的意思是我可以将一个堆叠在另一个之上,并且它们有不同的设置——(我已经尝试过他们不这样做)

这是我的图例部分代码:

handles = [mpl_patches.Rectangle((0, 0), 1, 1, fc="white", ec="white",
                                 lw=0, alpha=0)] * 4
lines = []
handles[0] = Line2D([0], [0], color='red',lw=3)
labels = []
labels.append("R² = {0:.2g}".format(Rsquared))
#labels.append("MSE = {0:.2g}".format(mse))
leg = ax.legend(handles, labels, loc='best', fontsize='x-large',
          fancybox=True, framealpha=0.7)

labels.append("RMSE = {0:.2g}".format(rmse))
labels.append("MAE = {0:.2g}".format(mae))

如果甚至有办法在图表上标记红线本身,那就太好了。这是图表本身的代码:

fig, ax = plt.subplots()
ax.scatter(y_test, y_predicted ,s=10,color='darkslateblue',linewidths=1)
ax.plot([y.min(), y.max()], [y.min(), y.max()], 'k-', lw=1.75)
ax.set_xlabel('Actual (%)',fontsize='large')
ax.set_ylabel('Predicted (%)',fontsize='large')
y_test, y_predicted = y_test.reshape(-1,1), y_predicted.reshape(-1,1)
ax.plot(y_test, LinearRegression().fit(y_test, y_predicted).predict(y_test), color="red", lw=1.75)

黑线是 y=x。

请帮忙!我已经在这几天了。这是一个很小的变化,但对我的报告至关重要。

【问题讨论】:

    标签: python matplotlib legend


    【解决方案1】:

    虽然我不能完全理解您实际需要什么或如何绘制您的确切数据,但我认为您的意思是简单地将您的图例分开?例如,使用您的代码,这是一个带有单独图例的虚拟图:

    plt.figure()
    
    handles = [
        Line2D([0], [0], color='red',lw=3),
        Line2D([0], [0], color='white',lw=3),
        Line2D([0], [0], color='white',lw=3)
    ]
        
    labels = []
    labels.append("R² = {0:.2g}".format(0.93))
    L1 = plt.legend(handles[:1], labels, loc='upper left', fontsize='x-large',
              fancybox=True, framealpha=0.7)
    ax = plt.gca().add_artist(L1)
    labels_ = []
    labels_.append("RMSE = {0:.2g}".format(0.033))
    labels_.append("MAE = {0:.2g}".format(0.023))
    
    plt.legend(handles[1:], labels_, loc='lower right', fontsize='x-large',
              fancybox=True, framealpha=0.7)
    plt.show()
    

    这会给出类似的结果:

    如果需要,请查看 matplotlib 的 Multiple legends on the same Axes 文档。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-20
      • 2012-03-12
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 2016-05-21
      相关资源
      最近更新 更多