1

I have a function for creating plots in R. I wish to print the unit along with feature name. Below is the code.

library(ggplot2)
plotfunction <- function(feature, featur_name, feature_unit){
  ggplot(aes(x = feature), data = mtcars) +
    geom_histogram(binwidth = 0.5) +
    labs(x = paste(featur_name, feature_unit), y = "Count, #")

}

plotfunction(mtcars$wt, "Displacement, ", expression({g}/{dm}^{3}))

The function produces the plot as as shown below.

enter image description here

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
JustCurious
  • 328
  • 2
  • 10

1 Answers1

0

Not the most graceful solution, but here goes:

plotfunction2 <- function(feature_name, feature_unit){

  x.lab = paste0("expression(paste('", feature_name, "', ", feature_unit, "))")

  ggplot(data = mtcars, aes(wt)) + 
    geom_histogram(binwidth = 0.5) +
    labs(x = eval(parse(text = x.lab)))
}

plotfunction2("Displacement, ", "{g}/{dm}^{3}")

plot

(I left the first argument out because data input isn't part of the real question here... though you probably shouldn't define the aesthetic mapping with the $ sign.)

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
  • Could you please explain this line. Not able to understand the mixed use of double and single quotes. `x.lab = paste0("expression(paste('", feature_name, "', ", feature_unit, "))")` **though you probably shouldn't define the aesthetic mapping with the $ sign** then how to pass variable name to function? – JustCurious Sep 12 '17 at 05:38
  • @JustCurious The result of the x.lab line is `"expression(paste('Displacement, ', {g}/{dm}^{3}))"`, the string form of a valid expression. When parsed & evaluated, `labs(x = eval(parse(text = x.lab)))` becomes `lab(x = expression(paste('Displacement, ', {g}/{dm}^{3})))`. – Z.Lin Sep 12 '17 at 05:52
  • Using `$` inside `aes()` affects ggplot's aesthetic mapping between the dataset & its variables. Answere [here](https://stackoverflow.com/questions/32543340/behavior-ggplot2-aes-in-combination-with-facet-grid-when-passing-variable-wi) explains it in detail. If you have to pass variable names in, you can use string version of variable name in `aes_string()` instead. [Here](https://stackoverflow.com/questions/23401681/ggplot-aes-string-does-not-work-inside-a-function) is an example of how it works. – Z.Lin Sep 12 '17 at 05:58