Hamza allal
Hamza allal

Reputation: 101

How to bold and to break text in two line of plt.annotate [python]

I calculated R-squared and the regression equation, and then plotted the graph, but my problem is:

1) I can not write my text "plt.annotate" in two lines.

2) I can not write ($R^2$) in bold

here is my script:

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

I hope the result should be like that :
y = 0.75x + 0.2
R^2 = 0.914

Upvotes: 0

Views: 2298

Answers (2)

MB-F
MB-F

Reputation: 23637

  1. Use \n for line breaks.
  2. \mathbf{} to use bold font in math mode (between $ $).

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

Upvotes: 1

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339122

You need to make the font bold inside the MathText command.

plt.annotate("$\mathbf{R}^\mathbf{2}$" ,...)

Example here:

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

Upvotes: 1

Related Questions