在图9中很容易获得数据的线性最佳拟合--使用stat_smooth(method="gls")。但是,我不知道如何使系数达到最佳拟合线或R2值。R中的Ggplot有一个stat_regline_equation()函数可以做到这一点,但我在plotnine中找不到类似的工具。
目前,我使用statsmodels.formula.api.ols来获取这些值,但在plotnine中必须有更好的方法。
附言:我对所有的编程都是新手。
发布于 2020-04-14 03:36:09
我最终使用了以下代码;不是PlotNine,但非常容易实现。
import plotnine as p9
from scipy import stats
from plotnine.data import mtcars as df
#calculate best fit line
slope, intercept, r_value, p_value, std_err = stats.linregress(df['wt'],df['mpg'])
df['fit']=df.wt*slope+intercept
#format text
txt= 'y = {:4.2e} x + {:4.2E}; R^2= {:2.2f}'.format(slope, intercept, r_value*r_value)
#create plot. The 'factor' is a nice trick to force a discrete color scale
plot=(p9.ggplot(data=df, mapping= p9.aes('wt','mpg', color = 'factor(gear)'))
+ p9.geom_point(p9.aes())
+ p9.xlab('Wt')+ p9.ylab(r'MPG')
+ p9.geom_line(p9.aes(x='wt', y='fit'), color='black')
+ p9.annotate('text', x= 3, y = 35, label = txt))
#for some reason, I have to print my plot
print(plot)https://stackoverflow.com/questions/61131266
复制相似问题