Python matplotlib legend- superscript 的字体和颜色

Font and colour for Python matplotlib legend- superscript

谁能帮我把R2写得和其他的一样?特别不是斜体。这是我的代码:

虽然我在这里,但谁能告诉我怎么做

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

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()

谢谢:)

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

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 创建包含红线的图例条目。 下面相应的代码会覆盖 handles[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)