2012-07-20 40 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