2010-07-04 39 views
1

我希望重新創建該圖: alt text http://had.co.nz/stat405/resources/drills/plot-drills/ggplots/hrline7.png重新創建ggplot的geom_smooth CI背景 - 在R基礎?

(從here

使用R基本圖形。

我不知道該怎麼做。有什麼建議? (我的動機是我想創建一個線寬(和/或顏色)將反映另一個維度的情節。到現在爲止 - ggplot2是我在R中找到的唯一一個如何做到這一點的地方。很高興能夠做到這一點也在基地R)

回答

2

好吧,我花了太多時間搞這個......注意最後一行是ggplot版本,所以你可以比較兩者。

#loess and error curves almost just like ggplot2 
op <- par(las=1, mar = c(3,3,1,1)) 
n <- 30 
x <- sort(rnorm(n)) #(varying density in predictor) 
x <- x + abs(min(x)) 
x <- x/max(x)*2*pi 
y <- sin(x)+rnorm(n) #(curvy) 
m <- loess(y~x) 
xx <- seq(min(x), max(x), (max(x)-min(x))/1000) #increase density of values to predict over to increase quality of curve 
f <- predict(m, xx, se = TRUE) 
ci <- f$se * qt(0.975, f$df) 
cih <- f$fit + ci 
cil <- f$fit - ci 
plot(x,y, ylim = c(min(cil,y), max(cih,y)), cex.axis = 0.85, xlab = '', ylab = '', type = 'n') 
title(xlab = 'x', ylab = 'y',line = 2) 
grid(col = 'gray') 
points(x,y, pch = 19, cex = 0.65) 
lines(xx, f$fit, col = 'blue', lwd = 1.2) 
xx <- c(xx, rev(xx)) 
yy <- c(cil, rev(cih)) 
polygon(xx, yy, col=rgb(0.1,0.1,0.1,0.25), border = NA) 
par(op) 

#qplot(x,y, geom = 'point') + stat_smooth() 
+0

令人印象深刻 - 你只是從你的其他答案中獲得了「獲勝的答案標記」。我希望你至少喜歡它:)(我很清楚你的第一句話,我用R做了很多事情......) – 2010-07-05 19:23:29

3

請參閱help(polygon)example(polygon)(尤其是布朗運動的例子) - 變化的寬度是相當普遍的一些領域,以顯示隨時間變化。

同樣的例子也demo(graphics)

## An example showing how to fill between curves. 

par(bg="white") 
n <- 100 
x <- c(0,cumsum(rnorm(n))) 
y <- c(0,cumsum(rnorm(n))) 
xx <- c(0:n, n:0) 
yy <- c(x, rev(y)) 
plot(xx, yy, type="n", xlab="Time", ylab="Distance") 
polygon(xx, yy, col="gray") 
title("Distance Between Brownian Motions") 
+0

謝謝dirk。有沒有辦法改變多邊形的不透明度? – 2010-07-04 16:53:52

+1

我會這樣想的。不是alpha,在支持的情況下,是通用顏色規範的第四個參數? – 2010-07-04 16:56:52

+0

第二次測試後:1)有沒有辦法創建曲線多邊形? 2)(冒着無知的風險)我要輸入什麼來達到「通用顏色規範」?謝謝德克! – 2010-07-04 17:38:13

1

而得到平滑的曲線,看loesspredict.loess

+0

謝謝哈德利.. – 2010-07-04 16:52:46

3

我不知道,如果準確複製圖有可能在基礎圖形。在網格圖形中是可能的。儘管如此,下面的代碼爲你提供了一個類似於你想要的東西的例子。將其調整到數據集。

n <- 20 
x <- rnorm(n) 
y <- rnorm(n) 
o <- order(x) 
x <- x[o] 
y <- y[o] 
m <- loess(y~x, span = 1) #ggplot seems to smooth more than default 
f <- predict(m, se = TRUE) 
ci <- f$se * qt(0.975, f$df) 
cih <- f$fit + ci 
cil <- f$fit - ci 
plot(x,y, ylim = c(min(cil,y), max(cih,y))) 
lines(x, f$fit, lwd = 2) 
xx <- c(x, rev(x)) 
yy <- c(cil, rev(cih)) 
polygon(xx, yy, col="#A9A9A930", border = NA) 
+0

謝謝你的代碼約翰。順便說一句,在電網中做這件事很容易? – 2010-07-04 20:31:20

+0

不知道...如果你想要整個事情,背景和一切,網格可能會更容易。我想知道格萊德是如何讓曲線如此平滑的。標準線條函數並不會像ggplot那樣平滑。我只是猜測,在網格中修復這個問題是因爲這是ggplot的基礎。但我真的不知道。 – John 2010-07-04 23:08:31

+2

對於此應用程序,基本和網格之間沒有區別。如果您想要更平滑的曲線,請使用更多的部分。 – hadley 2010-07-05 03:15:26

0

在GGPlot中將geom_ribbon成爲您所需要的?這將創建一個可變寬度線。

+0

謝謝Jesse,但是請注意我正在嘗試用base R來完成上面的操作。我接受。 – 2010-07-08 04:45:14