1

I would like to label a ggplot with a combination of LaTex expression, variable values, and normal text, e.g.

l_decile_names[vec_deciles[1]], " decile (", vec_items[item_current], ")"

whereby

  • l_decile_names contains LaTex: "1^{st}", ... "10^{th}"
  • vec_items contains strings "item A", "item B", "item C", ...

I can get it to work for a plot title, but not for labels. The aim is to plot the legend for the labels below the plot with its content left-aligned.

enter image description here

I tried various approaches with bquote(), expr() and TeX(), e.g.

labels = c("all subjects", 
         TeX(paste0(l_decile_names[vec_deciles[1]], " decile (", vec_items[item_current], ")")),
         TeX(paste0(l_decile_names[vec_deciles[2]], " decile (", vec_items[item_current], ")")))

... but without success yet. MWE provided below, help is greatly appreciated!

library(ggplot2)
library(latex2exp)

vec_deciles <- c(
  1,
  2
  # ...
)
l_decile_names <- list(
  '1stDecile' = '1^{st}',
  # ...
  '10thDecile' = '10^{th}'
)

# survey_items
vec_items <- c(
  "item A",
  "item B",
  "item C"
  # ...
)
item_current <- 3

vec_deciles_label <- paste(l_decile_names[vec_deciles[1]], "and", l_decile_names[vec_deciles[2]])

ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_boxplot() +
  labs(
    title=TeX((paste0("Scores of ", vec_deciles_label, " decile in ", vec_items[item_current]))),
    x="",
    y="Score"
  ) +
  scale_color_discrete(name = "Scores for ",
    labels = c("all subjects", 
               "1^{st} decile (item C)",
               "4^{th} decile (item C)"

    )) +
  theme(
        legend.box="vertical",
        legend.position="bottom"
  ) +
  guides(colour=guide_legend(ncol=1, nrow=3, byrow=TRUE))
bretauv
  • 7,756
  • 2
  • 20
  • 57
mavericks
  • 1,005
  • 17
  • 42
  • Does it have to be LaTex or would you accept anything that works? – Nova Jun 08 '20 at 14:06
  • Well, LaTex would be nice, such that more complex cases than the example above could be covered as well. But if the solution you have in mind works nicely both with HTML and PDF output that would clearly be an advantage! – mavericks Jun 08 '20 at 14:19
  • Have you attempted to use scales::label_ordinal? – Susan Switzer Jun 08 '20 at 15:03
  • [scales::label_ordinal](https://cran.r-project.org/web/packages/scales/scales.pdf) would likely allow to add `1^{st}", ... "10^{th}` to the label, as in this example. But what would you recommend for more sophisticated LaTex expressions? – mavericks Jun 08 '20 at 15:23
  • 1
    Try `labels = unname(c(...))`. Worked for me. See the second answer to https://stackoverflow.com/questions/44310088/how-to-add-latex-code-in-ggplot2-legend-labels – stefan Jun 08 '20 at 18:38
  • @stefan Thanks a lot for the hint, this works very well! Since the legend text came out right-aligned I had to add `theme(legend.text.align = 0)`. Would you like to add your solution to receive the points? – mavericks Jun 09 '20 at 05:13
  • interestingly, not all LaTex expressions are accepted, e.g. `"$\\Rightarrow$"` works while `"$\\Longrightarrow$"` surprisingly does not. – mavericks Jun 09 '20 at 05:35
  • also interesting, that `"$\\Rightarrow$"`requires the `$`sign while `"1^{st}"` does not – mavericks Jun 09 '20 at 05:37
  • Even further: when I compile my Rmd report in `thesisdown`/`huskyown` and include `"$\\Rightarrow$"` I get the following `error in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : failed to find or load PDF CID font`. This does not happen for `"1^{st}"` – mavericks Jun 09 '20 at 06:58
  • @mavericks if you solved your problem, could you detail the solution as an answer? – bretauv Jun 09 '20 at 08:23

1 Answers1

2

The answer is based on a comment from @Stefan who referred to this SO post.
Text-alignment in the legend can be achieved as recommended here by @konvas.

# ... see question above

ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_boxplot() +
  labs(
    title=TeX((paste0("Scores of ", vec_deciles_label, " decile in ", vec_items[item_current]))),
    x="",
    y="Score"
  ) +
  scale_color_discrete(name = "Scores for ",
                       labels =  
                         unname(TeX( # <== to be able to have label with LaTex expression + variable value + normal text
                           c(
                             "all subjects", 
                             paste0(l_decile_names[vec_deciles[1]], " decile (", "$\\Rightarrow \\ldots$ ", vec_items[item_current], ")"),
                             paste0(l_decile_names[vec_deciles[2]], " decile (", "$\\Rightarrow \\ldots$ ", vec_items[item_current], ")")
                           )
                         ))
  ) +
  theme(
    legend.box="vertical",
    legend.position="bottom",
    legend.text.align = 0 # <== to left-align the legend text
  ) +
  guides(colour=guide_legend(ncol=1, nrow=3, byrow=TRUE))

Plot_solution

Furthermore, I experienced the following limitations:

  1. not all LaTex expressions are accepted, e.g. "$\\Rightarrow$" works while "$\\Longrightarrow$" does not;
  2. some LaTex expressions require a $-sign, others do not, e.g. "$\\Rightarrow$" does while "1^{st}" does not;
  3. some LaTex expressions will work in R/Rmd output, but not in "more sophisticated Rmds" such as thesisdown/huskydown

Session info: MacOs 10.13.6, R 3.6.3, ggplot2_3.3.1, latex2exp_0.4.0

mavericks
  • 1,005
  • 17
  • 42