2

I'm writing a wrapper function around ggplot2 and having difficulty with one of the string arguments passed. Here's the sample code

myPlot <- function(tim, labx){
  ggplot(subset(dat,TIME=tim), aes(x=WT, y=Var))+
    geom_point(size=2)+
    facet_wrap(~Dose)+
    scale_x-continuous(expression(bold("Predicted"~labx~"Concentration ("*mu*"g/mL)")))
}

When I say myplot(100, "Week3"), my x-axis label is showing as "Predicted labx Concentration (µg/mL)" instead of "Predicted Week3 Concentration (µg/mL)". How do I fix this?

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
  • Welcome to Stack Overflow! Could you make your problem reproducible by sharing a sample of your data so others can help (please do not use `str()`, `head()` or screenshot)? You can use the [`reprex`](https://reprex.tidyverse.org/articles/articles/magic-reprex.html) and [`datapasta`](https://cran.r-project.org/web/packages/datapasta/vignettes/how-to-datapasta.html) packages to assist you with that. See also [Help me Help you](https://speakerdeck.com/jennybc/reprex-help-me-help-you?slide=5) & [How to make a great R reproducible example?](https://stackoverflow.com/q/5963269) – Tung Oct 24 '18 at 16:08

1 Answers1

1

One solution is to use bquote() instead of expression(), and use .() inside of bquote to evaluate character (string) variables.

Below is a fully reproducible example of the issue.

library(ggplot2)

labx = "Week3"

p = ggplot(data.frame(x=1:5, y=1:5), aes(x, y)) + 
    geom_point() + 
    xlab(bquote(bold(Predicted~.(labx)~Concentration~(mu*g/mL))))
p

enter image description here

bdemarest
  • 14,397
  • 3
  • 53
  • 56