0

I'd like to make a ggplot function that allows me to choose a dataset, the data on x and y axes, and the y-axis label as an expression, but I can't get the y-axis expression to be part of the function.

here's what I have so far:

x_vs_time <- function (data, xaxis, yaxis, yaxislabel) {
  
ggplot(data, aes(x = {{xaxis}}, 
                y= {{yaxis}}))+
  geom_point(size =3, alpha =0.5)+ 
  ylab (expression(yaxislabel)) 
  }

x_vs_time (alldata, daycount, nutrient_concentration, NO[3]~(mu*M))

When I run the function, the y-axis label appears as the variable name in the function,"yaxislabel", and I haven't been able fix it. I can include it as a normal label, but I have multiple expressions that I'd like to include in several plots, like :

  • ylab (expression (Si:NO3~drawdown))
  • ylab (expression (NO[3]~(mu*M)))
  • ylab (expression (Cells~L^-1))
  • etc.

Does anyone know how I can include the y-axis label expression in the function ?

1 Answer 1

3

Use substitute instead of expression. When you use expression, it captures the literal name inside the parentheses, whereas substitute will give you the actual argument that was passed to your function.

x_vs_time <- function (data, xaxis, yaxis, yaxislabel) {
  
ggplot(data, aes(x = {{xaxis}}, y = {{yaxis}})) +
  geom_point(size = 3, alpha = 0.5) + 
  ylab(substitute(yaxislabel))
}

Obviously, we don't have your data, but we can see this works using the built-in iris data set:

x_vs_time(iris, Sepal.Length, Sepal.Width, NO[3])

enter image description here

Or a different expression using mtcars

x_vs_time(mtcars, wt, mpg, Si:NO[3]~drawdown)

enter image description here

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

2 Comments

Do you know why ` ylab (deparse(substitute(yaxislabel)))` won't work here? Thanks.
@TarJae that will turn the expression into a string, so for example "NO[3]" . This will be used as a character argument and printed as-is. Keeping it as an expression will allow ggplot (actually grid) to parse it as a plotmath expression.

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.