JerryTheForester
JerryTheForester

Reputation: 476

How to add a character string as a code to ggplot object

A part of my code for ggplot is stored in a character vector. I would like to use this code as an additional geoms for my ggplot.

Example1:

  DF=data.frame(x=seq(1:10), y=seq(1:20))
   a='geom_line()'# This is a string that should be converted to RCode

So far I tried:

ggplot(DF, aes(x,y))+geom_point()+a
Error: Don't know how to add a to a plot

ggplot(DF, aes(x,y))+geom_point()+as.name(a)
Error: Don't know how to add as.name(a) to a plot

ggplot(DF, aes(x,y))+geom_point()+eval(parse(text=a))
Error in geom_line() + geom_line(y = 1) : 
non-numeric argument to binary operator

ggplot(DF, aes(x,y))+geom_point()+deparse(substitute(a))
Error: Don't know how to add deparse(substitute(a)) to a plot

Example 2:

DF=data.frame(x=seq(1:10), y=seq(1:20))
a='geom_line()+geom_line(y=1)'

Probable you are wondering, why I would like to do that in a first place? In a for loop, I created expressions and stored them in a list as characters. Later, I pasted together all expressions into a single string expression. Now, I would like to add this string to a ggplot command. Any suggestions?

Edit: Example 1 was successfully solved. But Example 2 stays unsolved.

Upvotes: 2

Views: 1495

Answers (2)

T X
T X

Reputation: 613

You can also use a function to define these code into a list. Please see: https://homepage.divms.uiowa.edu/~luke/classes/STAT4580/dry.html

Here I cited the related code:

Defining a theme_slopegraph function to do the theme adjustment allows the adjustments to be easily reused:

theme_slopechart = function(toplabels = TRUE) {
     thm <- theme(...)
list(thm, ...) # add multiple codes
#...
}

p <- basic_barley_slopes ## from twonum.R
p + theme_slopechart()

Upvotes: 0

the parse function has text argument you need to pass a to. Try:

ggplot(DF, aes(x,y)) + geom_point() + eval(parse(text = a))

More info here: http://adv-r.had.co.nz/Expressions.html#parsing-and-deparsing

In case of multiple statements, it is possible to deparse the original expression, add the new and then evaluate as a whole

original <- deparse(quote(ggplot(DF, aes(x,y)) + geom_point()))
new_call <- paste(original, '+', a)
eval(parse(text = new_call))

Upvotes: 3

Related Questions