【问题标题】:Font and colour for Python matplotlib legend- superscriptPython matplotlib 图例的字体和颜色 - 上标
【发布时间】:2020-08-15 14:07:13
【问题描述】:

有人能帮我把 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()

谢谢你:)

【问题讨论】:

  • 您可以使用 unicode 上标 2:"R²",而不是使用乳胶格式 ("$R^2$")。参见例如wikipedia.

标签: python matplotlib fonts legend italics


【解决方案1】:

对于第一个解决方案,实现它的一种可能方法是仅在数学环境中排版^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 的红线。 下面的相应代码覆盖了句柄[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)

【讨论】:

  • 非常感谢,我认为第二个效果更好。我还有一个愚蠢的问题。有没有办法让 RMSE 和 MAE 直接位于该线下方,因为它们不对应于彩色线。基本上将图例中的下两行向左移动?
  • 将参数markerfirst=False 添加到ax.legend 是一个合适的解决方案吗?
  • 非常感谢您的回答。通过将红线移到另一侧确实有效果,但其他所有内容仍然对齐,所以现在 RMSE 和 MAE 右侧有一个间隙
猜你喜欢
  • 2014-12-10
  • 1970-01-01
  • 2020-04-08
  • 2012-04-11
  • 1970-01-01
  • 1970-01-01
  • 2015-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多