0

I want to make a ggplot call variable to the user, without changing the ggplot call in the script...

I have a data frame with different columns I would love to use for label the dots on my plot. A lot of those columns are long and I want to provide a function 'shortname' to shorten the column a bit...

I also want to make this variable with a variable and this is where I stuck at the moment.

df <- data.frame(a=c('a;b;c','d;e;f'), b=c('A;B;C','D;E;F'),
                 x=c(1,2), y=c(2,3))

use_column <- 'b'
shortname <- function(x) {
  sub('([^;]+).*', '\\1', x)
}

g <- ggplot(df, aes(x,y)) + geom_point()
g + geom_text(aes(label=a))
g + geom_text(aes(label=shortname(a)))
g + geom_text(aes(label=shortname(b)))

Up to this point, everything works as expected. The first plots shows column a shortened and the second plot shows column b. But when I try to use the variable use_column, I don't get it to run...

g + geom_text(aes_string(label=shortname(use_column)))

I am running out of ideas and hope somebody can help me on this.

Thanks in advance!

1 Answer 1

1

The problem is that you use shortname on b, which returns b. Only then does the aes_string read the resulting b and uses the whole b for evaluating.

You can avoid this by using "shortname(b)" instead of shortname("b"). That is

g + geom_text(aes_string(label=paste('shortname(', use_column, ')')))

Alternatively, you could use aes together with get.

g + geom_text(aes(label=shortname(get(use_column))))
Sign up to request clarification or add additional context in comments.

1 Comment

Huh, this is still hard to read... Is there a way to make it more readable with aes()... I just used aes_string() during some testing... But at least it is a working solution, thanks for this!

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.