Cannot save plots as pdf when ggplot function is called inside a function

86 views Asked by At

I am going to plot a boxplot from a 4-column matrix pl1 using ggplot with dots on each box. The instruction for plotting is like this:

p1 <- ggplot(pl1, aes(x=factor(Edge_n), y=get(make.names(y_label)), ymax=max(get(make.names(y_label)))*1.05))+ 
  geom_boxplot(aes(fill=method), outlier.shape= NA)+ 
  theme(text = element_text(size=20), aspect.ratio=1)+
  xlab("Number of edges")+
  ylab(y_label)+
  scale_fill_manual(values=color_box)+
 geom_point(aes(x=factor(Edge_n), y=get(make.names(true_des)), ymax=max(get(make.names(true_des)))*1.05, color=method), 
              position = position_dodge(width=0.75))+
  scale_color_manual(values=color_pnt)

Then, I use print(p1) to print it on an opened pdf. However, this does not work for me and I get the below error:

Error in make.names(true_des) : object 'true_des' not found

Does anyone can help?

1

There are 1 answers

0
Jonathan Gilligan On BEST ANSWER

Your example is not very clear because you give a call but you don't show the values of your variables so it's really hard to figure out what you're trying to do (for instance, is method the name of a column in the data frame pl1, or is it a variable (and if it's a variable, what is its type? string? name?)).

Nonetheless, here's an example that should help set you on the way to doing what you want:

Try something like this:

pl1 <- data.frame(Edge_n = sample(5, 20, TRUE), foo = rnorm(20), bar = rnorm(20))

y_label <- 'foo'

ax <- do.call(aes, list(
    x=quote(factor(Edge_n)), 
    y=as.name(y_label), 
    ymax = substitute(max(y)*1.05, list(y=as.name(y_label)))))

p1 <- ggplot(pl1) + geom_boxplot(ax)
print(p1)

This should get you started to figuring out the rest of what you're trying to do.

Alternately (a different interpretation of your question) is that you may be running into a problem with the environment in which aes evaluates its arguments. See https://github.com/hadley/ggplot2/issues/743 for details. If this is the issue, then the answer might to override the default value of the environment argument to aes, for instance: aes(x=factor(Edge_n), y=get(make.names(y_label)), ymax=max(get(make.names(y_label)))*1.05, environment=environment())