Loop for ggplot2 to r formula

Here is an example:

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") 

I have more levels of variables listed above, instead of writing a long “+” formula, I can loop the process. Sorry for the simple question.

Edit: how to iterate over x or y variables in a formula

  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)))) 
+4
source share
2 answers

ggplot2 the way to do this is to always put data in a data frame and display aesthetics. This makes things a lot easier:

 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") 
+5
source

Try

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

All Articles