0

I am adding a point to a ggplot, how can I make the x and y coordinates as variables? I tried this code, but it does not work

func <- function(data){

  meanx <- mean(data[,1])
  meany <- mean(data[,2])

  p <- ggplot(data, aes(x = data[,1], y = data[,2]))
  p + 
  geom_point(size = 5, shape = 19, color = "#00FF00",
         aes(x = meanx, y = meany))

}

func(iris)

I have the following error:

Error in eval(expr, envir, enclos) : object 'meanx' not found

Can anyone help me please?

1
  • take a look at aes_string
    – Justin
    Nov 27, 2012 at 20:08

3 Answers 3

4

One solution would be to replace

geom_point(size = 5, shape = 19, color = "#00FF00", aes(x = meanx, y = meany)) 

with

annotate("point",size = 5, shape = 19, color = "#00FF00", x = meanx, y = meany)
0
3

The error message is due to meanx and meany not being part of the data frame data which is specified as value of the parameter data in the ggplot function.

It will work if you add the argument data = data.frame(meanx, meany) to geom_point.

0

One option is to use aes_string, like Justing says. This does exactly what you ask, use a string to assign aesthetics. However, it is better to, as Sven suggested, to just put the meanx and meany into a data.frame.

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.