Home > Software design >  ggplot2 bold for part of a facet_wrap label
ggplot2 bold for part of a facet_wrap label

Time:11-11

A paper now in page proofs has been modified by the copy editor to have figure tags (e.g. 'A', 'B', ...) in bold, while the rest of the label is normal. For example "A matches > 30", "B matches > 60". I cannot figure out how to get facet_wrap() labeller to bold only part of the label string. I have not figured out how to get labeller=label_parsed to accept my bold string with >= in it.

CodePudding user response:

As you provided no minimal reproducible example I don't know what's the issue with your code.

But here is a minimal reprex showing how you could achieve your desired result. Note the use of the ~ after bold

dat <- data.frame(
  x = 1,
  y = 1,
  facet = c("bold(A)~matches > 30", "bold(B)~matches >= 60")
)

library(ggplot2)

ggplot(dat, aes(x, y))  
  geom_point()  
  facet_wrap(~facet, labeller = label_parsed)

CodePudding user response:

I believe I have found a bug in plotmath/as_labeller. The script below shows the problem:

library(ggplot2)

f_vals = c(0.5, 0.8, 1.2, 1.5)
labs = c("A","B","C","D")

all_data=NULL

for (ix in 1:length(f_vals)) {
    dat <- data.frame(x=rnorm(20,mean=0,sd=f_vals[ix]),
        facet=f_vals[ix])

    all_data <- rbind(all_data,dat)
}
## this line fails with "sd:"
f_labs = sprintf("bold(%s)~~~the~sd ==~%.2f",labs, f_vals)
names(f_labs) = f_vals

facet_labeller = as_labeller(f_labs, label_parsed)

pA = ggplot(all_data, aes(x, x))  
  geom_point()  
  theme(strip.text=element_text(hjust=0))  
  facet_wrap(~facet, labeller = facet_labeller)

pdf(file="test_bold3.pdf",width=8.0, height=6.0)
pA

As written, this code works as expected. But if there is a colon (:) in the label string, e.g.

f_labs = sprintf("bold(%s)~~~the~sd: ==~%.2f",labs, f_vals)

The script fails with the message:

Error in parse(text = as.character(values)) : 
  <text>:1:19: unexpected '=='
1: bold(A)~~~the~sd: ==
                      ^
Calls: <Anonymous> ... labeller -> default -> lapply -> FUN -> FUN -> parse
Execution halted

I was unable to find a combination of spaces and '~' that allowed a ':' in the label string.

  • Related