在注释中使用不同的字体样式(ggplot2)
Using different font styles in annotate (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")
在该图表上,我想将 粗体字体 应用于文本注释中短语的第一部分:
This should be bold
但我希望文本的其余部分在字体和样式方面保持不变。
如何使用 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")
如果将它分成两个注释没有问题,您可以这样做:
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")
另一个可能的解决方案是使用 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")
我正在使用下面的代码生成带有一些注释的简单图表:
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")
在该图表上,我想将 粗体字体 应用于文本注释中短语的第一部分:
This should be bold
但我希望文本的其余部分在字体和样式方面保持不变。
如何使用 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")
如果将它分成两个注释没有问题,您可以这样做:
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")
另一个可能的解决方案是使用 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")