在注释中使用不同的字体样式(ggplot2)

Kon*_*rad 22 charts text annotations r ggplot2

我正在使用下面的代码生成带有一些注释的简单图表:

require(ggplot2); data(mtcars)
ggplot(mtcars, aes(x = wt, y = mpg)) + 
  geom_point() +
  annotate("text", x = 4, y = 25, label = "This should be bold\nand this not",
           colour = "red") +
  geom_vline(xintercept = 3.2, colour = "red")
Run Code Online (Sandbox Code Playgroud)

简单的情节

在该图表上,我想将粗体字体应用于文本注释中短语的第一部分:

这应该是大胆的

但我希望文本的其余部分在字体和样式方面保持不变.

小智 31

如果您在两个注释中将其拆分没有问题,您可以这样做:

annotate("text", x = 4, y = 25, label = "This should be bold",
       colour = "red", fontface =2)+
annotate("text", x = 4, y = 24, label = "and this not",
       colour = "red")
Run Code Online (Sandbox Code Playgroud)


aos*_*ith 20

如何使用plotmath语法parse = TRUE:

ggplot(mtcars, aes(x = wt, y = mpg)) + 
    geom_point() +
    annotate("text", x = 4, y = 25, 
            label = 'atop(bold("This should be bold"),"this should not")',
            colour = "red", parse = TRUE) +
    geom_vline(xintercept = 3.2, colour = "red")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • @Konrad虽然它可能取决于我想要添加到绘图中的所有这些信息,但我可能会将每行放在data.frame或其他内容中并使用`tableGrob`和`annotation_custom`将其放在图形上在哪里我想要它. (2认同)

ETe*_*ddy 6

另一种可能的解决方案是使用ggtext package

library(ggtext)
library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg)) + 
  geom_point() +
  geom_richtext(aes(x = 4, y = 25, 
                    label = "**This should be bold**<br>and this not",
                    col = "red"),  
                fill = NA,
                label.color = NA) +
  geom_vline(xintercept = 3.2, colour = "red") +
  theme(legend.position = "none")
Run Code Online (Sandbox Code Playgroud)