r - 将方程添加到绘图上的回归线

标签 r ggplot2

好的,所以我想将回归线方程添加到我的图中。 我发现this answer由于某种原因,这对我不起作用。这是我的数据的样子:

>Plot_Data
   Treatment      value Substrate
1    Control 0.16666667  10.00000
2    Control 0.03333333   2.00000
3    Control 0.02380952   1.00000
4    Control 0.01388889   0.50000
5    Control 0.01250000   0.25000
6    Control 0.01219512   0.12500
7    Control 0.01176471   0.03125
8     +Inh P 0.50000000  10.00000
9     +Inh P 0.14285714   2.00000
10    +Inh P 0.10000000   1.00000
11    +Inh P 0.08333333   0.50000
12    +Inh P 0.07142857   0.25000
13    +Inh P 0.06666667   0.12500
14    +Inh P 0.06250000   0.03125
15    +Inh Q 0.43103448  10.00000
16    +Inh Q 0.08403361   2.00000
17    +Inh Q 0.05494505   1.00000
18    +Inh Q 0.02610966   0.50000
19    +Inh Q 0.02000000   0.25000
20    +Inh Q 0.01470588   0.12500
21    +Inh Q 0.01265823   0.03125

我使用了 awnsere 中建议的函数的稍微修改版本(我添加了 y 和 x 作为输入):

lm_eqn <- function(y,x,df){
    m <- lm(y ~ x, df);
    eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2, 
                     list(a = format(coef(m)[1], digits = 2), 
                          b = format(coef(m)[2], digits = 2), 
                          r2 = format(summary(m)$r.squared, digits = 3)))
    as.character(as.expression(eq));
}

然后我用以下方法绘制图表:

Plot <- ggplot(Plot_Data,aes(x=Substrate,y=value,group=Treatment,color=Treatment))+
geom_point(shape=1)+
geom_smooth(method = lm,fullrange =T,se=F,size=0.75)+
xlab(expression("[S]"^-1))+
ylab(expression("V"[0]^-1))+
xlim(c(-1.5,10))+
ggtitle("Adenylate Kinase rate graph")+
theme(axis.title = element_text(size=12),
      plot.title = element_text(hjust = 0.5))+
geom_text(x=5,y=0.5,
label = lm_eqn(Data.Inverse$Substrate,Data.Inverse$X.Inh.P,Data.Inverse),color = "red")

但我得到以下输出作为文本字符串,未经修改:

enter image description here

有什么想法吗?表达式功能似乎无法正常工作,但我不明白为什么。

编辑:

Data.Inverse 是数据帧 Plot_Datamelt 编辑(也使用 rep 添加了 Substrate 和 mutate),它看起来像:

Substrate    Control    X.Inh.P    X.Inh.Q
1  10.00000 0.16666667 0.50000000 0.43103448
2   2.00000 0.03333333 0.14285714 0.08403361
3   1.00000 0.02380952 0.10000000 0.05494505
4   0.50000 0.01388889 0.08333333 0.02610966
5   0.25000 0.01250000 0.07142857 0.02000000
6   0.12500 0.01219512 0.06666667 0.01470588
7   0.03125 0.01176471 0.06250000 0.01265823

最佳答案

根据the documentation ,需要 geom_text()parse 参数,以便“标签将被解析为表达式并按照plotmath 中的描述进行显示”。您忽略了它,这应该是正确的调用:

geom_text(
    x = 5,
    y = 0.5,
    label = lm_eqn(Data.Inverse$Substrate,Data.Inverse$X.Inh.P,Data.Inverse),
    color = "red",
    parse = TRUE
)

关于r - 将方程添加到绘图上的回归线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48847857/

相关文章:

r - 提高ggplot2 r中geom_text条目的分辨率

r - 如何更改R中的条形图和Y轴之间的距离

r - 将 x 轴放在 ggplot2 图表的顶部

r - 什么是 SockJSAdapter 以及为什么它无休止地运行

r - 为什么 testthat 中的 helper 文件来源两次

r - 如何使用ggplot2在几个pdf页面中获取图表

r - geom_bar 和 coord_flip 上的 ggplotly 似乎失败

r - 使用方程而不是数据点在ggplot中绘制多项式曲线

r - R中xtabs和聚合之间的na.action不一致

r - 如何在R的直方图中添加平均值?