Seaborn: annotate the linear regression equation

xkcvk2511 picture xkcvk2511 · Aug 27, 2017 · Viewed 15.1k times · Source

I tried fitting an OLS for Boston data set. My graph looks like below.

How to annotate the linear regression equation just above the line or somewhere in the graph? How do I print the equation in Python?

I am fairly new to this area. Exploring python as of now. If somebody can help me, it would speed up my learning curve.

Many thanks!

OLS fit

I tried this as well.

enter image description here

My problem is - how to annotate the above in the graph in equation format?

Answer

Serenity picture Serenity · Aug 27, 2017

You can use coefficients of linear fit to make a legend like in this example:

import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats

tips = sns.load_dataset("tips")

# get coeffs of linear fit
slope, intercept, r_value, p_value, std_err = stats.linregress(tips['total_bill'],tips['tip'])

# use line_kws to set line label for legend
ax = sns.regplot(x="total_bill", y="tip", data=tips, color='b', 
 line_kws={'label':"y={0:.1f}x+{1:.1f}".format(slope,intercept)})

# plot legend
ax.legend()

plt.show()

enter image description here

If you use more complex fitting function you can use latex notification: https://matplotlib.org/users/usetex.html