我使用annotation_custom()在我的图下方添加文本。但是,我无法弄清楚如何减小字体大小。绝望地,我尝试了geom_text(size= 8)哪个不起作用并且annotation_custom(size=8)不采用“大小”参数。如何更改annotation_custom()的字体大小?
df <- data.frame(x=seq(1:100), y=sort(rexp(100, 2)))
p= ggplot(df, aes(x=x, y=y)) +
geom_point()+
theme(plot.margin = unit(c(1,1,3,1), "cm"))+
ggtitle('Random Plot')
Text1 = textGrob('Additional suggestions:')
p1 = p + annotation_custom(grob = Text1, xmin = 0.2, xmax = 0.2, ymin = -0.3, ymax = -0.3)
gt <- ggplotGrob(p1)
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.newpage()
grid.draw(gt)
Run Code Online (Sandbox Code Playgroud)
任何信息都会非常有帮助。
正如 @Camille 在评论中所说,您可以使用函数的gp参数,如下所示:gpar(fontsize=8)annotation_custom
library(ggplot2)
library(grid)
df <- data.frame(x=seq(1:100), y=sort(rexp(100, 2)))
p= ggplot(df, aes(x=x, y=y)) +
geom_point()+
theme(plot.margin = unit(c(1,1,3,1), "cm"))+
ggtitle('Random Plot')
Text1 = textGrob('Additional suggestions:', gp = gpar(fontsize=8))
p1 = p + annotation_custom(grob = Text1, xmin = 0.2, xmax = 0.2, ymin = -0.3, ymax = -0.3)
gt <- ggplotGrob(p1)
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.newpage()
grid.draw(gt)
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用annotate中的函数ggplot2。确保您clip使用 进行协调coord_cartesian。这是一些可重现的代码:
p= ggplot(df, aes(x=x, y=y)) +
geom_point()+
theme(plot.margin = unit(c(1,1,3,1), "cm"))+
ggtitle('Random Plot') +
coord_cartesian(xlim = c(min(df$x), max(df$x)),
ylim = c(min(df$y), max(df$y)), clip = "off") +
annotate("text", x = 0.2, y = -0.3, label = "Additional suggestions:", size = 5)
p
Run Code Online (Sandbox Code Playgroud)

创建于 2023-09-20,使用reprex v2.0.2