2012-07-20 63 views
4

下面是一個例子:迴路GGPLOT2式中的R

require(ggplot2) 
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() 

yintercept <- c(5, 12, 20, 28, 29, 40) 
col <- c("red", "blue", "green", "pink", "yellow", "tan") 

# for the first level yintercept, and col 
p + geom_hline(aes(yintercept = 5), col = "red") 

我有變量更多級如上所列,而不是寫長「+」式,能予迴路的過程。對不起,簡單的問題。

編輯:

myd <- data.frame (y = rnorm (100, 5, 10), X1 = rnorm (100, 5, 1), 
    X3 = rnorm (100, 10, 2), X4 = rnorm (100, 50,4)) 

x <- c("X1", "X2", "X3", "X4") 

p <- ggplot(myd, aes(y = y)) + 
mapply (function (x) (geom_point(x = aes_string (x)))) 

回答

5

GGPLOT2辦法做到這一點是總是投放數據在數據框中繪製美學圖。它使事情變得更簡單:

df <- data.frame(yint = yintercept) 

# for the first level yintercept, and col 
p + geom_hline(data = df,aes(yintercept=yint,colour = factor(yint))) + 
    scale_colour_manual(values = col,guide = "none") 
+0

感謝您的好回答,我仍然質疑x或y aes的名稱是否仍然可以與顏色或攔截相同...請參閱我最近的編輯 – rdorlearn 2012-07-20 02:29:43

+0

原則上可以完成這種事情,儘管可能不是你勾畫的方式。然而,這通常不是一個好方法(至少不是你提供的例子)。唯一的例外是,如果它或多或少的不可能將數據安排在數據框中,但是你沒有提供一個例子來說明情況。 – joran 2012-07-20 02:35:19

+0

看到最近的例子,如果這個工程 – rdorlearn 2012-07-20 02:45:19

4

如何循環的X或Y變量的公式中嘗試

p+mapply(function(a,b){dum<-aes_string(yintercept=a); 
         geom_hline(dum, col = b)},a=yintercept,b=col) 
+0

你不需要分號。 – Dason 2012-07-20 00:53:49