包含带有较低或等号符号的表达式的标签的粗体

boldface of labels containing an expression with lower or equal symbol

我需要以粗体显示图表图例的标签。其中一个标签是包含“小于或等于”符号的表达式。

这是我的起点:

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"))

这样,第一个标签是粗体,第二个不是。按照建议 here 我尝试使用 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"))

标签仅在“<=”符号之前以粗体呈现。我还尝试将字符串的第二部分放在 bold():

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

但无济于事。感谢任何帮助。

隐藏在 plotmath 文档中的内容如下:

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.

相反,建议的方法是使用 unicode(假设字体和设备支持),在这种情况下,这意味着我们可以完全放弃 plotmath

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"))

虽然对于这个特定问题有点矫枉过正,但包 ggtext 使 ggplot2 中的复杂标签变得容易得多。它允许使用 Markdown 和 HTML 语法来呈现文本。

这是编写图例文本标签的一种方法,使用 Markdown 的 ** 加粗,使用 HTML 的 &le; 作为符号。

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())

(我在 Windows 机器上,默认的 windows 图形设备在向符号添加额外空格时可能会出现问题。使用 ragg::agg_png() 可以避免保存绘图时出现的问题,而且下一个版本的 RStudio 将允许您 change the graphics backend 绕过这些问题。)