Kenneth Lim
Kenneth Lim

Reputation: 13

Referencing stored variables in ggplot function

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

Upvotes: 1

Views: 190

Answers (1)

Marius
Marius

Reputation: 60170

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)

Upvotes: 1

Related Questions