Search code examples
rggplot2dplyrrlang

Non Standard Evaluation with ggplot2 in R


I have a fairly simple function below which takes a data frame and a column in that data frame as arguments. The function plots the column in the data frame on the y-axis vs. the "year" column on the x-axis. It will then display the values for the column in question alongside its points on the plot.

df_to_plot = data.frame(year = c(2011, 2012, 2013), data=c(0.22334, 0.345345, 0.456234))

makePlotFunc = function(df, y_var)
{
    ggplot(df, aes_(x=as.name("year"), y = as.name(y_var), group=1, label=as.name(y_var))) + geom_point() + geom_line() + geom_text()
}

makePlotFunc(df_to_plot, data)

You'll notice the "data" column, though, has a lot of decimal points. I want to be able to round those decimal points so it looks nice when those data points are displayed on the plot. Normally, when NOT using "non-standard evaluation" it could be done quite easily in the geom_text() like so:

geom_text(aes(round(data, 2))

Because I made this into a function using non standard evaluation, it cannot be done like this, though.

geom_text(aes_(round(as.name(y_var), 2)))

This throws an error.

non-numeric argument to mathematical function

I solved my issue by creating a new column in the data frame which serves as a label like so.

df_to_plot = mutate(df_to_plot, label = as.character(round(data, 2)))

Nevertheless, I am still interested if anybody knows how I could do it using non standard evaluation.


Solution

  • Thank you to MrFlick for your answer. It worked!

    geom_text(aes_(label=bquote(round(.(as.name(y_var)), 3))))