0

有人可以帮我让 R2 的写作看起来像其他人吗?尤其不是斜体。这是我下面的代码:

当我在这里时,谁能告诉我怎么做

  • 用红色书写 R2=0.97 线,以表明这就是图表上的红线或
  • 在该行的图例中插入红线/红色破折号?

我在网上看到过其他的方法,但我格式化我的图例的方式不允许这样做。

plt.rcParams["font.family"] = "Cambria"
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=2,)
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=2)
ax.set_title('H2O REF')
handles = [mpl_patches.Rectangle((0, 0), 1, 1, fc="white", ec="white",
                                 lw=0, alpha=0)] * 4
labels = []
labels.append("$R^2$ = {0:.2g}".format(Rsquared))
labels.append("RMSE = {0:.2g}".format(rmse))
labels.append("MAE = {0:.2g}".format(mae))
ax.legend(handles, labels, loc='best', fontsize='x-large',
          fancybox=True, framealpha=0.7,
          handlelength=0, handletextpad=0)
plt.show()

在此处输入图像描述

谢谢 :)

4

1 回答 1

0

对于第一个解决方案,实现它的一种可能方法是仅^2在数学环境中排版,而不是将第一个标签文本设置red此处所述,请参见下面的代码。

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as mpl_patches

x = np.linspace(0, 1)
y = x + np.random.normal(scale=0.1, size=50)

plt.rcParams["font.family"] = "Cambria"
Rsquared = 0.9
rmse = 0.8
mae = 1

fig, ax = plt.subplots()
ax.scatter(x, y)
ax.plot(x, x, c='r')

handles = [mpl_patches.Rectangle((0, 0), 1, 1, fc="white", ec="white",
                                 lw=0, alpha=0)] * 4

labels = []
labels.append("R$^2$ = {0:.2g}".format(Rsquared))
labels.append("RMSE = {0:.2g}".format(rmse))
labels.append("MAE = {0:.2g}".format(mae))
leg = ax.legend(handles, labels, loc='best', fontsize='x-large',
          fancybox=True, framealpha=0.7,
          handlelength=0, handletextpad=0)

texts = leg.get_texts()
texts[0].set_color("red")

或者,您可以使用Line2D创建图例条目,包括红线。下面的相应代码覆盖了句柄[0]。

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as mpl_patches
from matplotlib.lines import Line2D

x = np.linspace(0, 1)
y = x + np.random.normal(scale=0.1, size=50)


plt.rcParams["font.family"] = "Cambria"
Rsquared = 0.9
rmse = 0.8
mae = 1

fig, ax = plt.subplots()
ax.scatter(x, y)
ax.plot(x, x, c='r')

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')
labels = []
labels.append("R$^2$ = {0:.2g}".format(Rsquared))
labels.append("RMSE = {0:.2g}".format(rmse))
labels.append("MAE = {0:.2g}".format(mae))
leg = ax.legend(handles, labels, loc='best', fontsize='x-large',
          fancybox=True, framealpha=0.7)
于 2020-08-15T14:46:50.343 回答