分享

ggplot2添加公式标签

 阿越就是我 2023-10-12 发布于上海
     Try to learn everyhting about something! 

今天学习下如何在ggplot2中添加公式标签。

绘制函数曲线

对于绘制简单的函数曲线是非常简单的,R语言内置常见的各种概率分布函数,比如正态分布、均匀分布、二项分布等,前缀无非是d/p/r/q ,分别代表密度函数/分布函数/随机函数/分位数函数。

ggplot2中,只要使用stat_function()即可,非常简单。

library(ggplot2)

p <- ggplot(data.frame(x = c(-3,3)), aes(x = x))

p + stat_function(fun = dnorm)
plot of chunk unnamed-chunk-1
p + stat_function(fun = runif)
plot of chunk unnamed-chunk-2

除了自带的函数外,也支持自定义函数。

myfun <- function(x) {
  x^2 + 5*x + 2
}

ggplot(data.frame(x = c(-10,10)),aes(x = x)) + 
  stat_function(fun = myfun) +
  annotate("text", x = -5, y = 100, parse = T,
           label = "'Function: ' * y == x^2 + 5*x + 2",
           color = "red", size = 8
           )
plot of chunk unnamed-chunk-3

画出数学表达式

实现方式是很简单的,使用annotate()即可实现。可能最大的拦路虎是不知道公式在R中应该怎么打出来,但是好像没有什么特别好的办法,只能是把自己常用的背下来。

library(ggplot2)

p <- ggplot(data.frame(x = c(-3,3)), aes(x = x)) +
  stat_function(fun = dnorm)

p + annotate("text", x = 2, y = 0.3, parse = T,
             label = "frac(1, sqrt(2 * pi)) * e ^ {-x^2 / 2}"
             )
plot of chunk unnamed-chunk-4

下面再来一个例子,注意表达式中要用"*"链连接两个部分。

p + annotate("text", x=0, y=0.05, parse=TRUE, size=4,
label="'Function: ' * y==frac(1, sqrt(2*pi)) * e^{-x^2/2}")
plot of chunk unnamed-chunk-5

下面是一个帮助函数,可以帮助大家随时查看各种数学符号的写作方法

?plotmath
?demo(plotmath)

添加阴影

ggplot(data.frame(x = c(-3,3)), aes(x = x)) +
  stat_function(fun = dnorm, geom = "area", fill = "orange",alpha = 0.3)
plot of chunk unnamed-chunk-7

如何在部分区域绘制阴影呢?只需要把不想绘制的区域的值改为NA即可。

dnorm_limit <- function(x) {
  y <- dnorm(x)
  y[-2 < x & x < 2] <- NA
  return(y)
}

ggplot(data.frame(x = c(-3,3)), aes(x = x)) +
  stat_function(fun = dnorm_limit, geom = "area", fill = "orange",alpha = 0.3) +
  stat_function(fun = dnorm)
plot of chunk unnamed-chunk-8

或者使用闭包函数来解决,这是一个能够编写函数的函数。

limit_range <- function(fun, min, max) {
  function(x) {
    y <- fun(x)
    y[x > min & x < max] <- NA
    return(y)
  }
}

这样就可以用这个函数来生成需要的函数和值了。

aa <- limit_range(dnorm, -2,2)

aa(-5:5)
##  [1] 1.486720e-06 1.338302e-04 4.431848e-03 5.399097e-02           NA
##  [6]           NA           NA 5.399097e-02 4.431848e-03 1.338302e-04
## [11] 1.486720e-06

把我们的闭包函数带入即可使用。

ggplot(data.frame(x = c(-3,3)), aes(x = x)) +
  stat_function(fun = dnorm) +
  stat_function(fun = limit_range(dnorm, -2,2), geom = "area", fill = "red", alpha = 0.4)
plot of chunk unnamed-chunk-11

OK,完活儿!

以上就是今天的内容,希望对你有帮助哦!欢迎点赞、在看、关注、转发

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章