如何在ggplot2中将曲线添加到散点图?
问题描述:
我正在对扑热息痛过量进行审核。我创建了摄入后血液浓度与时间的散点图。这很简单:然而,治疗是由他们的血液水平是高于还是低于y=1986*0.840897^t
,其中t
是时间,y
=值为t=4:16
的血液水平。如何在ggplot2中将曲线添加到散点图?
如何在的散点图上叠加这样的函数?
基本上我想创造的东西有点像这样:
答
定义自己的函数,把它传递给stat_function()
和你所有的设置。
set.seed(357)
# simulate some data, rnorm() is used to add some noise
x <- seq(from = 4, to = 6, length.out = 10)
y <- 1986*0.840897^x + rnorm(10, sd = 30)
xy <- data.frame(x, y)
# define function
myfun <- function(x) 1986*0.840897^x
library(ggplot2)
ggplot(xy, aes(x = x, y = y)) +
theme_bw() +
geom_point() +
stat_function(fun = myfun)