Claudio
Claudio

Reputation: 1528

boldface of labels containing an expression with lower or equal symbol

I need to render in boldface the labels of the legend of a graph. One of the labels is an expression containing a "lower or equal" sign.

This is where I started from:

library(ggplot2)

df <- data.frame(x=factor(rep(0:1, 10)), y=rnorm(10), z=factor(rep(0:1, 10)))

ggplot(df, aes(x, y, shape=z)) +
geom_point() +
scale_shape_discrete(labels=c("Age > 65", expression(Age <= 65))) +
theme(legend.text=element_text(face="bold"))

In this way, the first label is bold, but the second is not. Following the suggestion here I tried to use plotmath bold():

library(ggplot2)

df <- data.frame(x=factor(rep(0:1, 10)), y=rnorm(10), z=factor(rep(0:1, 10)))

ggplot(aes(x, y, shape=z)) +
geom_point() +
scale_shape_discrete(labels=c("Age > 65", expression(bold(Age <= 65)))) +
theme(legend.text=element_text(face="bold"))

The label is rendered in bold only up to the "<=" sign. I have also tried to put the second part of the string within bold():

expression(bold(Age bold(<= 65)))

but to no avail. Any help is appreciated.

Upvotes: 0

Views: 471

Answers (2)

aosmith
aosmith

Reputation: 36076

While it is a little overkill for this particular issue, package ggtext makes complicated labels in ggplot2 a lot easier. It allows the use of Markdown and HTML syntax for text rendering.

Here's one way to write your legend text labels, using Markdown's ** for bolding and HTML's &le; for the symbol.

library(ggtext)

ggplot(df, aes(x, y, shape=z)) +
     geom_point() +
     scale_shape_discrete(labels=c("**Age > 65**", "**Age &le; 65**")) +
     theme(legend.text=element_markdown())

enter image description here

(I'm on a Windows machine, and the default windows graphics device can have problems with adding extra spaces to symbols. Using ragg::agg_png() avoids the issue when saving plots, but also the next version of RStudio will allow you to change the graphics backend to bypass these problems.)

Upvotes: 0

lroha
lroha

Reputation: 34291

Tucked away in the plotmath documentation is the following:

Note that bold, italic and bolditalic do not apply to symbols, and hence not to the Greek symbols such as mu which are displayed in the symbol font. They also do not apply to numeric constants.

Instead, a suggested approach is to use unicode (assuming font and device support) which, in this case, means we can dispense with plotmath altogether.

ggplot(df, aes(x, y, shape=z)) +
  geom_point() +
  scale_shape_discrete(labels=c("Age > 65", "Age \U2264 65")) +
  theme(legend.text=element_text(face="bold"))

Upvotes: 3

Related Questions