我想绘制一个函数 - 例如一条线 - 在散点图内。我编写的代码既可以单独执行,又可以将它们组合在一起?我的实验返回了错误消息。
我的代码如下:
library(ROSE)
data(hacide)
train <- hacide.train
ggplot(train, aes(x1, x2, colour = cls)) +
geom_point(size = 3, alpha = 0.4)
db <- function(x, beta1, beta2, alpha){-alpha/beta2 - x * beta1/beta2}
ggplot(data.frame(x = c(-4, 4)), aes(x = x)) +
stat_function(fun = db, args = list(-1.642354, -1.596056, -6.004609), colour = "blue" , size = 2)
但是如何将线与散点图叠加/组合?
您的建议将不胜感激。
答案 0 :(得分:0)
这就是你要找的东西吗?
ggplot(data.frame(x = c(-4, 4)), aes(x = x)) +
stat_function(fun = db, args = list(-1.642354, -1.596056, -6.004609), colour = "blue" , size = 2)+
geom_point(data = train, aes(x1, x2, colour = cls), size = 3, alpha = 0.4)
答案 1 :(得分:0)
最简单的方法是将功能添加到原始图中。 ggplot2
中的图表是按层构建的,这意味着您可以在构建图形时添加更多图层。
对于您的代码,您可以这样做:
library(ROSE)
data(hacide)
train <- hacide.train
db <- function(x, beta1, beta2, alpha){-alpha/beta2 - x * beta1/beta2}
ggplot(train, aes(x1, x2, colour = cls)) +
geom_point(size = 3, alpha = 0.4) +
stat_function(fun = db, args = list(-1.642354, -1.596056, -6.004609),
colour = "blue" , size = 2)
或将其添加到现有地块:
library(ROSE)
data(hacide)
train <- hacide.train
plot = ggplot(train, aes(x1, x2, colour = cls)) +
geom_point(size = 3, alpha = 0.4)
db <- function(x, beta1, beta2, alpha){-alpha/beta2 - x * beta1/beta2}
plot + stat_function(fun = db, args = list(-1.642354, -1.596056, -6.004609),
colour = "blue" , size = 2)