xkc*_*511 10 python matplotlib linear-regression python-3.x seaborn
我尝试为波士顿数据集安装OLS.我的图表如下所示.
如何在线上方或图中某处注释线性回归方程?如何在Python中打印方程式?
我是这个领域的新手.到目前为止探索python.如果有人可以帮助我,它会加快我的学习曲线.
非常感谢!
我也尝试过这个.
我的问题是 - 如何在方程式格式中对图中的上述进行注释?
Ser*_*ity 18
您可以使用线性拟合系数来制作类似于此示例的图例:
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()
Run Code Online (Sandbox Code Playgroud)
如果您使用更复杂的拟合功能,您可以使用乳胶通知:https://matplotlib.org/users/usetex.html
要在使用的情况下注释多条线性回归线,seaborn
lmplot
可以执行以下操作。
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_excel('data.xlsx')
# assume some random columns called EAV and PAV in your DataFrame
# assume a third variable used for grouping called "Mammal" which will be used for color coding
p = sns.lmplot(x=EAV, y=PAV,
data=df, hue='Mammal',
line_kws={'label':"Linear Reg"}, legend=True)
ax = p.axes[0, 0]
ax.legend()
leg = ax.get_legend()
L_labels = leg.get_texts()
# assuming you computed r_squared which is the coefficient of determination somewhere else
slope, intercept, r_value, p_value, std_err = stats.linregress(df['EAV'],df['PAV'])
label_line_1 = r'$y={0:.1f}x+{1:.1f}'.format(slope,intercept)
label_line_2 = r'$R^2:{0:.2f}$'.format(0.21) # as an exampple or whatever you want[!
L_labels[0].set_text(label_line_1)
L_labels[1].set_text(label_line_2)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8297 次 |
最近记录: |