2016-12-01 82 views
2

使用R,我想繪製一些數據點和他們的曲線(這是用神經網絡訓練的決策邊界)。首先我用正常情節功能做了它,但現在我想用ggplot2看起來更加花哨。R ggplot2:我如何繪製一個隱式函數(只有一個級別的輪廓線)?

這是它看起來就像沒有ggplot(注意曲線尤其是,該點是不太相關的):

Image

ggplot中繪製點是沒有問題的,但現在我要添加曲線爲好,這是由以下函數描述:

1.91*(1/(1+exp(-(23.50+12.64*x-24.54*y))))-1.95*(1/(1+exp(-(73.51-12.36*x-10.01*y)))) + 0.98 = 0 

這是通過兩個變量只是函數等於零,如3倍2Y = 0例如。正如你可以看到這個很難在ay = ...形式中重寫,所以我想通過在等級= 0處使用等高線圖來繪製等式。 它在我的散點圖上使用了curve3d:

curve3d(1.91*(1/(1+exp(-(23.50+12.64*x-24.54*y))))-1.95*(1/(1+exp(-(73.51-12.36*x-10.01*y)))) + 0.98 = 0, sys3d="contour",levels=0, add=TRUE) 

現在我真的想用ggplot2來達到同樣的效果。我嘗試了stat_contour地塊,但他們似乎沒有采取功能,並且不允許只選擇一個級別。所以:

  1. 有沒有什麼辦法用ggplot在等式形式(如ax + by = 0但可能更復雜)中繪製函數?
  2. 我可以使用數據點將這樣的繪製曲線添加到我的geom_point ggplot嗎?

編輯:這裏是一個代碼示例重新創建我的數據:

# data 
x1 <- rnorm(200, 3, .28) 
y1 <- rnorm(200, 3, .28) 
x2 <- rnorm(100, 3.45, .15) 
y2 <- rnorm(100, 3.35, .15) 
x3 <- rnorm(100, 3.3, .15) 
y3 <- rnorm(100, 2.4, .15) 

groups <- c(rep("H",200), rep("A",100), rep("B",100)) 
data <- data.frame(x = c(x1,x2,x3), y = c(y1,y2,y3), group = groups) 

# the working ggplot 
windows() 
ggplot(data, aes(x=x,y=y)) + xlim(2,4) + ylim(2,4) + geom_point(aes(color = group)) + scale_shape_manual(values=c(1,16)) 

# the old plot that I would like to plot with ggplot over the previous one with as well (doesn't work) 
curve3d(1.91*(1/(1+exp(-(23.50+12.64*x-24.54*y))))-1.95*(1/(1+exp(-(73.51-12.36*x-10.01*y)))) + 0.98, xlim=c(2,4), ylim=c(2,4), sys3d="contour",levels=0, add=TRUE) 
與此數據

所以,我想繪製功能1.91*(1/(1+exp(-(23.50+12.64*x-24.54*y))))-1.95*(1/(1+exp(-(73.51-12.36*x-10.01*y)))) + 0.98 = 0(或任何其他隱函數,如5x+2y=0無需重寫它)。

+0

如果您提供樣本[可重現示例](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)與樣本相比更容易幫助您輸入值。定義所有變量,以便我們可以嘗試重新創建該圖以測試可能的解決方案。 – MrFlick

+0

我明白了,我只是添加了一個代碼示例。 – sds

回答

1

tl; dr你唯一真正想念的是breaks=0。 基地情節:

g0 <- ggplot(data, aes(x=x,y=y)) + xlim(2,4) + ylim(2,4) + 
    geom_point(aes(color = group)) + scale_shape_manual(values=c(1,16)) 

產生輪廓數據(無圖紙任何東西):

cc <- emdbook::curve3d(1.91*(1/(1+exp(-(23.50+12.64*x-24.54*y))))- 
       1.95*(1/(1+exp(-(73.51-12.36*x-10.01*y)))) + 0.98, 
       xlim=c(2,4), ylim=c(2,4), sys3d="none") 

重新組織數據成數據幀:

dimnames(cc$z) <- list(cc$x,cc$y) 
mm <- reshape2::melt(cc$z) 

繪製與breaks=0

g0 + geom_contour(data=mm, 
        aes(x=Var1,y=Var2,z=value),breaks=0, 
        colour="black") 

enter image description here