Home > Software design >  Combine expression with function in ggplot
Combine expression with function in ggplot

Time:03-27

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 ?

CodePudding user response:

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

  • Related