1

Say I have a dataframe:

df <- data.frame(x=1:10, y=4:13)
p <- ggplot(df,aes(x,y)) + geom_point()    

Now I want to add many things to this graph, so I use a big paste function and print the output. Just as an example, say I wanted to add the word 'bananas' inside the x axis label.

x <- "bananas"    
print(paste0("+ xlab('Price of", x[1], "')"), quote=F)

If I try:

p + print(paste0("+ xlab('Price of", x[1], "')"), quote=F)

then it obviously does not work. But is there a way of adding the output of this function to the ggplot object 'p' without cutting/pasting from the console?

i.e. so we automatically can execute:

p + xlab('Price ofbananas')
0

1 Answer 1

1

If you want to add Price of bananas as the x label, then:

p + xlab(paste0("Price of ", x[1]))

Remember you're adding the xlab, so that should be your outside function. Inside it, you add/create the label you want. No need to print.

Update:

I think what you want is eval(parse(text=xxx)). For example:

add <- paste0("xlab('Price of ", x[1], "')")
p + eval(parse(text=add))

Note that I removed the + from the text, because you need it next to p to connect with eval.

I'm not sure why you would do this, but it works.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm looking for a more general solution - I have numerous additional themes/labels/etc to add inside of a function.
Then just store the output in variables.
I guess I understood what you want: You want the code xlab() and others to be stored inside a variable and them add them all at once, right?

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.