如何将函数添加到 ggplot2 中具有不同映射的散点图

How to add a function to a scatter plot with different mappings in ggplot2

我有一个可以用指数函数很好地描述的小数据集,如果我首先使用对数变换获得适当的起始值,我可以求解这个函数的参数:

x <- c(seq(from = 10, to = 200, by = 10), seq(from = 230, to = 590, by = 30))
y <- c(32.403, 38.832, 46.023, 59.895, 75.385, 98.283, 134.474, 186.62, 243.293,
       307.713, 383.845, 468.155, 567.619, 684.183, 810.969, 969.507, 1135.038,
       1320.475, 1530.365, 1757.032, 2587.402, 3633.337, 4939.983, 6526.32, 8436.739,
       10679.428, 13280.434, 16259.746, 19651.199, 23636.122, 27849.712, 32704.141, 38291.655)

simulationData <- data.frame(x = x, y = y)
model.0 <- lm(log(y) ~ x, data=simulationData)
start <- list(a=exp(coef(model.0)[1]), b=coef(model.0)[2])
model <- nls(y ~ a * exp(b * x), data = simulationData, start = start)
qplot(x, y, data = augment(model)) + geom_line(aes(y = .fitted)) +
  theme(text = element_text(size=20), axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

但是,此 qplot 命令仅绘制我拥有的相对有限的 x 值向量的拟合值,因此曲线实际上仅由线段组成,看起来并不平滑。

我可以生成更精细的 x 值网格,并使用 nls 模型的参数绘制平滑函数:

dense_x <- seq(0.1, 600, by = 0.1)
df <- data.frame(dense_x)
ggplot(df,aes(dense_x))+
  stat_function(fun=function(dense_x) 10.34436 * exp(0.00719 * dense_x)) +
  theme(text = element_text(size=20), axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
  theme_bw()

但我不知道如何组合这两个图,因为它们有单独的映射(一个是原始数据,我想将其作为点包含在图中,另一个是曲线数据拟合,我只想用它来绘制这个函数)。

有谁知道生成这样一个图的合适方法。也许有一种方法可以只标记 x 值的一个子集以包含在 geom_point() 调用中?

谢谢!

您应该能够将数据分配和 x/y 值从 ggplot 移动到您想要绘制的几何图形。因此,与其在全局范围内继承它们,不如为每个单独的 geom 分配不同的数据和美学。这样你就可以组合不同的地块——即使是相同类型的几何层:

ggplot() +
geom_scatter(df1, aes(x1, y1)) +
geom_scatter(df2, aes(x2, y2))

或者,正如您在评论中建议的那样,您可以将不同的图层添加到您在 ggplot() 函数中定义数据和映射的现有绘图中,并简单地为这个新图层指定一个新的数据集和映射。