1

I want to make a function that will add a label to an existing plot (built in ggplot2) and position the label based on a ratio of the X and Y values of the data. However, when I create variables h and v in my function, they aren't recognized outside the function. Is there a way around this?

alphabet = data.frame("X"=c(1,2,3), "Y"=c(1,2,3), "Label"=c("A", "B", "C"))
plot = ggplot(data = alphabet, aes(x = X, y = Y)) + geom_point()

addLabel = function(d, p, row) {
  h = max(d$X)*0.5
  v = max(d$Y)*0.5

  p = p + geom_text(data=d[row,], aes(x = X+h, y = Y+v, label = Label))

  return(p)
}

addLabel(alphabet, plot, 1)

### Returns:
Error in eval(expr, envir, enclos) : object 'h' not found
2
  • Look into geom_text. plot + geom_text(aes(label="Label")) Commented Aug 29, 2017 at 21:12
  • 1
    Or add them to the dataset. e.g., d$h = max(d$X)*0.5 Commented Aug 29, 2017 at 21:16

1 Answer 1

1

ggplot will always work best if you put the values you're using in the dataframe. Something like:

addLabel = function(d, p, row) {
    row_d = d[row, ]
    row_d$h = max(row_d$X)*0.5
    row_d$v = max(row_d$Y)*0.5

    p = p + geom_text(data=row_d, aes(x = X+h, y = Y+v, label = Label))

    return(p)
}

addLabel(alphabet, plot, 1)
Sign up to request clarification or add additional context in comments.

Comments

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.