How to add R squared (R^2) in matplotlib?

Viewed 1139

I want to calculate and add R^2 and R in my line chart as a legend, but I only know how to add equations in the chart. Here is my code.My English is poor,I make a mistake in the last question,I don't want to reject your approve.I'm sorry,I hope you can see this question.


import matplotlib.pyplot as plt  
import numpy as np 
import pylab as pl 
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)  
plt.plot(x,p(x), "y--") 
plt.plot(x, y, 'og-', label=("y=%.6fx+(%.6f)"%(z[0],z[1]))) 
plt.legend()
2 Answers

You can calculate and plot R^2 as follows given your code:

from sklearn.metrics import r2_score
import matplotlib.pyplot as plt  
import numpy as np 
import pylab as pl 
import pylab
y = df["rain"]  
x = df["SITE"] 

z = np.polyfit(x, y, 1)  
p = np.poly1d(z)  
r_squared = r2_score(x, y)

fig, ax = plt.subplots() 
ax.plot(x, y) 
ax.set(xlabel='year', ylabel='P', title='rain') 
ax.grid() 

pylab.plot(x,p(x), "y--") 
pl.plot(x, y, 'og-', label=("y=%.6fx+(%.6f) - $R^2$=%.6f"%(z[0],z[1], r_squared))) 
pl.legend()

You can try "$r^2$" (or any combination in a f-string). The $ renders Latex chars in matplotlib labels:

x = np.arange(0, 100)
y = x**2
plt.figure(figsize=(15,10))
plt.plot(x, y, label="y=$x^2$")
plt.legend()

Image illustrating Latex rendering on Matplotlib

Related