如何在plt.annotate [python]的两行中加粗和打破文本

时间:2017-11-20 10:57:30

标签: python-3.x numpy matplotlib

我计算了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()

enter image description here

我希望结果应该是这样的:
y = 0.75x + 0.2
R ^ 2 = 0.914

2 个答案:

答案 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")

enter image description here

答案 1 :(得分:1)

  1. 使用\n换行。
  2. \mathbf{}在数学模式下使用粗体字体(在$ $之间)。
  3. E.g:

    plt.annotate('first line\nsecond line\n$x=42$ $\mathbf{R^2}$ = 0', 
                 xy=(0.5, 0.5), fontsize=12, fontweight="bold")
    

    enter image description here