Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

strip.text does not work with labeller – facet_wrap ggplot2

I am using facet_wrap and need expression in header so I am using labeller. But then strip.text does not work (I want the header to be in bold). see code:

sc <- c("Ref","DJ","DT","DTHW")
vars <- c("O2","PO4","NH4","NO3")
df1 <- data.frame(scenario=rep(sc,4),variable=rep(vars,each=4),pct=runif(16,-10,10))

ggplot(df1, aes(y= scenario, x=pct)) +
  geom_col(aes( fill = scenario), position = position_dodge()) + 
  facet_wrap(vars(variable)) +
  theme (strip.text = element_text(face = "bold"))

This gives bold header as expected:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But if I add the expression with labeller:

vars2plot <- c(expression(paste("Hypol. ",O[2])),expression(paste("Epil. ",PO[4]^"3-")),
               expression(paste("Epil. ",NH[4]^"+")), expression(paste("Hypol. ",NO[3]^"-")))
names(vars2plot) <- vars
df1$variable <- factor(df1$variable, levels = vars, labels = vars2plot)

ggplot(df1, aes(y= scenario, x=pct)) +
  geom_col(aes( fill = scenario), position = position_dodge()) + 
  facet_wrap(vars(variable), labeller = labeller(variable=label_parsed)) +
  theme (strip.text = element_text(face = "bold"))

The bold does not appear:

enter image description here

Any ideas how to make the header bold?

>Solution :

If you use expressions, then you need to use the plotmath syntax to make things bold. You cannot use font properties to alter the appearance. You can wrap your expressions in bold() with

vars2plot <- c(expression(paste("Hypol. ",O[2])),expression(paste("Epil. ",PO[4]^"3-")),
               expression(paste("Epil. ",NH[4]^"+")), expression(paste("Hypol. ",NO[3]^"-")))

# or simplified ...
# vars2plot <- expression(
#   "Hypol. " ~ O[2],
#   "Epil. " ~ PO[4]^"3-",
#   "Epil. " ~ NH[4]^"+",
#   "Hypol. " ~ NO[3]^"-")

# now make them all bold
vars2plot <- as.expression(lapply(vars2plot, function(x) bquote(bold(.(x)))))

which will output
bold expressions in facet strips

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading