0

I want to add R^2 and R in my line chart.But I just know how to add equation in the chart.Here is my code.Thanks a lot!

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from sympy import S, symbols, printing
import pylab as pl
# Data for plotting
y = df["rain"]
x = df["SITE"]

fig, ax = plt.subplots()
ax.plot(x, y)

ax.set(xlabel='year', ylabel='P',
       title='rain')
ax.grid()

z = np.polyfit(x, y, 1)
p = np.poly1d(z)
pylab.plot(x,p(x),"y--")




pl.plot(x, y, 'og-', label=("y=%.6fx+(%.6f)"%(z[0],z[1])))
pl.legend() 
Jan
  • 4,974
  • 3
  • 26
  • 43
chant
  • 25
  • 1
  • 9
  • 1
    You mean how to calculate it? If so, take a look here: https://stackoverflow.com/questions/893657/how-do-i-calculate-r-squared-using-python-and-numpy – wagnifico Apr 11 '21 at 15:26
  • Thanks,and could you tell me how to add R^2 in my line chart as label ,I couldn't do it.I don't know how to do it. – chant Apr 12 '21 at 08:40
  • You can modify your string, something like: `label=("y=%.6fx+(%.6f), R2=%.2f"%(z[0],z[1],Rsquare)`, where `Rsquare` is the value. Also, you can use an annotation to add the text in the plot (you may check the [matplolib's website](https://matplotlib.org/stable/gallery/text_labels_and_annotations/annotation_demo.html) for examples). – wagnifico Apr 14 '21 at 15:42
  • OK,thanks a lot! I will have a try and check some examples. – chant Apr 15 '21 at 12:17

0 Answers0