我计算了R平方和回归方程,然后绘制了图表,但我的问题是:
1)我不能用两行写“plt.annotate”文本。
2)我不能用粗体
写($ R ^ 2 $)这是我的剧本:
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
y = [1, 2, 2, 4, 5, 4, 6, 4, 6, 7, 9, 10, 11, 12, 15]
n = len(x)
x = np.array(x)
y = np.array(y)
sumx = sum(x)
sumy = sum(y)
sumx2 = sum(x*x)
sumy2 = sum(y*y)
sumxy = sum(x*y)
promx = sumx/n
promy = sumy/n
m = (sumx*sumy - n*sumxy)/(sumx**2 - n*sumx2)
b = promy - m*promx
sigmax = np.sqrt(sumx2/n - promx**2)
sigmay = np.sqrt(sumy2/n - promy**2)
sigmaxy = sumxy/n - promx*promy
R2 = (sigmaxy/(sigmax*sigmay))**2
print(m, b)
print(R2)
plt.plot(x, y,'bo', label='H1')
plt.plot(x, m*x + b, 'r-')
plt.xlabel('x')
plt.ylabel('y')
#plt.grid()
plt.annotate('y = ' + str(round(m,4)) + 'x + ' + str(round(b,4)) + ' ; ' + '$R^2$ = ' + str(round(R2,3)), xy=(1.2, 11.5), fontsize=12, fontweight="bold")
plt.legend(loc=4)
plt.show()
我希望结果应该是这样的:
y = 0.75x + 0.2
R ^ 2 = 0.914
答案 0 :(得分:1)
您需要在MathText命令中使字体变为粗体。
plt.annotate("$\mathbf{R}^\mathbf{2}$" ,...)
此处示例:
tx = "y = {:.4f}x + {:.4f}\n$\mathbf{{R}}^\mathbf{{2}}$ = {:.4f}"
plt.annotate(tx.format(m,b,R), xy=(1.2, 11.5), fontsize=12, fontweight="bold")
答案 1 :(得分:1)