这是一个例子:
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")
Run Code Online (Sandbox Code Playgroud)
我有更多级别的变量,如上所列,而不是写长"+"公式,我可以循环过程.对不起,简单的问题.
编辑:如何循环公式中的x或y变量
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))))
Run Code Online (Sandbox Code Playgroud)
该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")
Run Code Online (Sandbox Code Playgroud)