2017-07-19 80 views
0

我想繪製一個函數 - 例如,一條線 - 在散點圖內。我編寫了兩個獨立的代碼,但我怎樣才能將它們組合起來?我的實驗返回了錯誤消息。如何在ggplot的散點圖上繪製函數

我的代碼如下:

library(ROSE) 
data(hacide) 
train <- hacide.train 

散點圖

ggplot(train, aes(x1, x2, colour = cls)) + 
    geom_point(size = 3, alpha = 0.4) 

enter image description here

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) 

enter image description here

但如何疊加/結合線與散點圖?

您的建議將不勝感激。

回答

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) 
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)