4

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 as listed above, instead of writing long "+" formula, can I loop the process. Sorry for simple question.

Edits: how to loop over the x or y variables in the 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))))

2 Answers 2

5

The ggplot2 way to do this is to always put data in a data frame and map the aesthetic. It makes things much simpler:

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")
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the great answer, I have still question if name of x or y aes can be still looped in the same as colour or intercept...see my recent edits
That sort of thing can be done, in principle, though probably not the way you sketched out. However, that usually isn't a good way to go about things (at least not for the sort of example you provide). The only exception would be if its more or less impossible to arrange your data in a data frame, but you haven't provided an example where that would be the case.
4

Try

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

1 Comment

You don't need the semicolon.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.