R语言画图——添加数学表达式和R2(Ⅱ)

R语言画图——添加数学表达式和R2(Ⅱ)

前言

胸卡没有想到随手写的博客竟然得到了那么多的关注!

一天的访问量直接破千,而且还得到了大神的鼓励!(激动)

估计大家是被这个标题吸引。(哈哈)

果然,天下苦R添加数学表达式久矣

然而,第二篇博客还有很多细节没有完善,这次附上代码和精讲。

以后,胸卡会分享平时画图的一些小技巧,欢迎喜欢R语言的朋友一起交流。

那我们直接进入正题!

正文

一般我们在R上使用 geom_smooth()函数来添加一系列的平滑曲线。

但是某些参考书给出的方法实在是有限,而且超级不好用。

胸卡在初次使用R作图的时候也是被搞得很难受,找了好久的代码。

这次,直接使用stat_function()函数完成作图。

首先,给出代码:

a <- c(1, 2, 3, 4, 5)
b <- c(5, 4, 3, 2, 1)

c <- data.frame(a, b)

library(ggplot2)

p <- ggplot(data = c, aes(x = a, y = b)) + 
        geom_point() + 
        geom_smooth(method = "lm", color = "red")

p

图1如下:
在这里插入图片描述
通过拟合得知:函数为y = -x + 6 , R^2 = 1

我们可以通过 stat_function()函数直接拟合曲线。
代码如下:

p <- ggplot(data = c, aes(x = a, y = b)) + 
  geom_point() + 
  stat_function(fun = function(x)-1*x+6, color = "orange", size = 1) 

p

图2如下:
在这里插入图片描述

最后,使用annotate()函数添加文本。

p <- ggplot(data = c, aes(x = a, y = b)) + 
  geom_point() + 
  stat_function(fun = function(x)-1*x+6, color = "orange", size = 1) +
  annotate("text", x = 4, y = 5, parse = TRUE, 
           label = "y == -x+6", size = 4) +
  annotate("text", x = 4, y = 4.5, parse = TRUE, 
           label = "atop(R^2==1)", size = 4) 
  
p

图3如下:
在这里插入图片描述

补充1:上下标代码

在图3中,我们还用到了上标代码,atop()函数。
同时,在这里也给出下标的代码。

p <- ggplot(data = c, aes(x = a, y = b)) + 
  geom_point() + 
  stat_function(fun = function(x)(-1)*x+6, color = "orange", size = 1) +
  annotate("text", x = 4, y = 5, parse = TRUE, 
            label = "y == -x+6", size = 4) +
  annotate("text", x = 4, y = 4.5, parse = TRUE, 
            label = "atop(R^2==1)", size = 4) +
  annotate("text", x = 4, y = 4, parse = TRUE,    #下标
            label = "x[1]==x[2]", size = 4)
  
p

如图:
在这里插入图片描述

补充2 其他函数

如果是其他函数则直接这样编写代码:

#指数函数
stat_function(fun = function(x)1.5015*exp(x*(-0.009)), size = 1)  +
annotate("text", x = 25, y = 2.5, parse = TRUE,  label = "y == 1.5015*e^{-0.009*x}")

#二次函数:
stat_function(fun = function(x)-90.613*x+630.42*x^2+4.3696, size = 1) +
annotate("text", x = 0.09, y = 2.51, parse = TRUE, label = "y == 630.42*x^{2}-90.613*x+4.3696") 

#注意:这里的上标使用{
    
    }表达

有不明白的地方,欢迎在评论区讨论,也请大家批评指正。

猜你喜欢

转载自blog.csdn.net/m0_46461702/article/details/112497727