将回归线方程添加到PLOTNINE中的facet_wrap

问题描述 投票:0回答:1

我正在尝试添加适合绘制数据的线性方程的方程。我使用了 geom_smooth 和方法 'lm' 以及公式 = 'y~x'。 将方程添加到单个图显示了如何将其添加到单个图,但是,我的查询是在处理facet_wrap或facet_grid时如何将方程添加到图九?

下面给出了可行的示例:

import plotnine as p9
from scipy import stats
from plotnine.data import mtcars as df

# create plot
plot=(p9.ggplot(data=df, mapping= p9.aes('wt','mpg', color = 'factor(gear)'))
    + p9.geom_point(p9.aes())
    + p9.facet_wrap('~ gear')
    + p9.xlab('Wt')+ p9.ylab(r'MPG')
    + p9.geom_smooth(method='lm', formula = 'y~x', se=False)
     )
print(plot)

上述站点给出的单个图的解决方案是:

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)

这里讨论了在 R 中使用 ggplot 的相同内容:add eq to facet in R

我不确定如何在plotnine中实现这一点。

python linear-regression facet-wrap annotate plotnine
1个回答
0
投票

ggplot2
实现这一目标的方法是创建一个数据框,其中一列包含分面变量的类别(确保使用与主数据相同的列名称),第二列包含您想要的标签添加到每个方面。然后可以在
geom_text
中使用该数据框来添加标签。

import plotnine as p9
import pandas as pd
from scipy import stats
from plotnine.data import mtcars as df

def model(df):
    slope, intercept, r_value, p_value, std_err = stats.linregress(df['wt'],df['mpg'])

    return pd.Series({'slope' : slope, 'intercept' : intercept, 'r2_value' : r_value**2, 'p_value' : p_value, 'std_err' : std_err })

df_labels = df.groupby('gear').apply(model).reset_index()
df_labels = df_labels.rename(columns = {'index' : 'gear'})

string = 'y = {:4.2e} x + {:4.2E};   R^2= {:2.2f}'
df_labels['txt'] = [string.format(*r) for r in df_labels[['slope', 'intercept', 'r2_value']].values.tolist()]

# create plot
plot=(p9.ggplot(data=df, mapping= p9.aes('wt','mpg', color = 'factor(gear)'))
    + p9.geom_point(p9.aes())
    + p9.geom_text(p9.aes(label = 'txt'), data = df_labels, x = 5.5, y = 35, color = 'black', va = 'top', ha = 'right')
    + p9.facet_wrap('~ gear', ncol = 1)
    + p9.xlab('Wt')+ p9.ylab(r'MPG')
    + p9.geom_smooth(method='lm', formula = 'y~x', se=False)
     )
print(plot)

© www.soinside.com 2019 - 2024. All rights reserved.