0

I am trying to add text inside the below graph using figtext() but the written code below does not work. I appreciate any help. enter image description here

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
x = np.array([0.00161, 0.00322, 0.00483, 0.00645, 0.00806])
y = np.array([0.005, 0.006, 0.007, 0.008, 0.013])

a, b = np.polyfit(x, y, 1)
slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
slope = round(slope, 4)
intercept = round(intercept, 4)
r_value = r_value
r_squared = round(r_value ** 2, 4)

plt.scatter(x, y, color='purple')
plt.figtext(-25, 25, f"y={slope}x+{intercept}")
plt.figtext(-25, 25, f"R^2={r_squared}")
plt.text(1, 17, 'y = ' + '{:.2f}'.format(b) + ' + {:.2f}'.format(a) + 'x', size=14)
plt.xlabel("Concentration")
plt.ylabel("Absorbance")
plt.title("Phosphorus Calibration Curve")
plt.plot(x, a*x+b, color='steelblue', linestyle='--', linewidth=2)

plt.show()
Nisa Aslan
  • 37
  • 4
  • 3
    Did you try reading the [`figtext`](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.figtext.html) docs first, specifically around what the `x` and `y` parameters expect? The same goes for `plt.text`. – BigBen Dec 03 '21 at 20:24
  • 1
    `ax = plt.gca()` and `ax.text(...)` is probably more adequate. – JohanC Dec 03 '21 at 20:30

1 Answers1

1

The problem, as I think, is in x and y coordinates that you used.

Coordinates in plt.figtext (without transformation) are in figure coordinates, i.e. floats between 0 and 1. This detail looks another way in plt.text, where the default is data coordinates.

In my opinion, you should not "mix" both methods.

Using figure coordinates and calls only to plt.figtext I changed your drawing code to:

plt.scatter(x, y, color='purple')
plt.xlabel('Concentration')
plt.ylabel('Absorbance')
plt.title('Phosphorus Calibration Curve')
plt.plot(x, a * x + b, color='steelblue', linestyle='--', linewidth=2)
plt.figtext(0.15, 0.83, f'y = {slope}x + {intercept}')
plt.figtext(0.15, 0.77, f'R^2 = {r_squared}')
plt.figtext(0.15, 0.7,  f'y = {b:.4f} + {a:.4f}x', size=14)
plt.show()

getting:

enter image description here

Adjust the above coordinates any way you wish.

But if you want use plt.text, use data coordinates. E.g. change the last plt.figtext to

plt.text(0.0015, 0.0112,  f'y = {b:.4f} + {a:.4f}x', size=14)

and you will get similar result.

Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41