-1

I am creating ggplots with label strings from a list, sometimes adjusted with an if-else function depending on content. If the title contains superscript or subscript I am parsing the title to get the required format. However, when adding a ggtitle with a parsed string the bold part of the theme is not implemented.

In the simplest form this is what i am working with:

library(ggplot2) #charts
library(gridExtra)

df <- data.frame(Letter_x=c(LETTERS[1:3]), Value_y=c(1:3))

my_title1 = parse(text="NO[3]")
my_title2 = "NO3"

plot_theme = theme(
    plot.title = element_text(size = 14, face = "bold", margin=margin(0, 0, 3, 0), hjust=.5)
)

p1 <- ggplot(df, aes(Letter_x, Value_y)) +
    geom_point() +
    ggtitle(my_title1)+
    plot_theme

p2 <- ggplot(df, aes(Letter_x, Value_y)) +
    geom_point() +
    ggtitle(my_title2)+
    plot_theme

grid.arrange(p1, p2, ncol=2, nrow = 1)

I would like both resulting charts to have bold titles:

Charts with different title font-weight

enter image description here

jrcalabrese
  • 2,184
  • 3
  • 10
  • 30
  • 1
    Please provide enough code so others can better understand or reproduce the problem. – Community Mar 12 '23 at 14:27
  • 1
    Please make this question *reproducible*. This includes enough sample code you've attempted to create the plots (including listing non-base R packages, and any errors/warnings received), sample *unambiguous* data (e.g., `data.frame(x=...,y=...)` or the output from `dput(head(x))`), and intended output given that input. Refs: https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info. – r2evans Mar 12 '23 at 15:17
  • Sorry, I have now edited the question. – Martin Liungman Mar 12 '23 at 17:56

1 Answers1

0

This seems like a really problematic area for ggplot and I hope someone will come up with a definitive solution. After some digging I've come up with this solution changing the my_title1 object using plotmath, and I suspect the final answer lies in this vein somewhere if this is not it. Perhaps more can be done as it still seems the subscript portion is not bold? Hard to tell.

 my_title1 <- expression(paste(bold("NO"[3])))
  
  p1 <- ggplot(df, aes(Letter_x, Value_y)) +
    geom_point() +
    ggtitle(my_title1)+
    plot_theme
  p1

My other suggestion would be if you can mutate your data and use faceting then the labeller() comes in to play. I have not tested that it will work with type face but I have used it for parsing labels.

dandrews
  • 967
  • 5
  • 18
  • Thanks for the effort! I think I found the optimal solution: use regular format. It requires no solving effort and minimal code change. Also, the bold format was never any pretty! :) – Martin Liungman Mar 13 '23 at 19:27
  • It seems an area that should be addressed though. Perhaps I'm missing something but the lack of other suggestions would indicate no one else has a solution. – dandrews Mar 13 '23 at 23:35