ggplot:使用 strip.text.x (element_text) 仅制作小平面轴标签的一个元素 "bold"

ggplot: Using strip.text.x (element_text) for making only one element of the facet axis label "bold"

我只想在顶部 x 轴标签(在构面面板中)的第一个元素 上使用粗体 。这可以使用 element_text 函数来完成。但是,当我执行以下操作时,facet 中的所有元素都变为 "bold",而我只希望第一个元素为粗体。

p3 <- ggplot(mtcars, aes(wt, mpg)) + geom_point() + facet_wrap(~ cyl)
p3 + theme(strip.text.x = 
           element_text(colour = "white", face = c("bold", "plain", "plain")))

因此,在这里,我只希望顶部的标签“4”为粗体

使用 Grob

p3 <- ggplot(mtcars, aes(wt, mpg)) + geom_point() + facet_wrap(~ cyl)
p3 <- p3 + theme(strip.text.x = 
           element_text(colour = "white", face = c("bold", "plain", "plain")))
grob <- ggplotGrob(p3)
elem <- grob$grobs$strip_t.1
elem

NULL

grid.ls(getGrob(elem, "strip.text.x.text", grep=TRUE))$name

Error in getGrob(elem, "strip.text.x.text", grep = TRUE) : it is only valid to get a child from a "gTree"

library(ggplot2)
library(grid)
p3 <- ggplot(mtcars, aes(wt, mpg)) + geom_point() + facet_wrap(~ cyl) +
                 theme(strip.text.x = element_text(colour = "white"))
grob <- ggplotGrob(p3)
print(grob) 
# ...
# 17  2 ( 6- 6, 4- 4) strip-t-1-1                                   gtable[strip]
# 18  2 ( 6- 6, 8- 8) strip-t-2-1                                   gtable[strip]
# 19  2 ( 6- 6,12-12) strip-t-3-1                                   gtable[strip]
# ...

# The first strip grob is at position 17
k <- 17
# Here I increase font size for a better visualization of the bold font
grob$grobs[[k]]$grobs[[1]]$children[[2]]$children[[1]]$gp$fontsize <- 20
# Set again white color for strip text
grob$grobs[[k]]$grobs[[1]]$children[[2]]$children[[1]]$gp$col <- "white"
# Set bold font
grob$grobs[[k]]$grobs[[1]]$children[[2]]$children[[1]]$gp$font <- as.integer(2)
attr(grob$grobs[[k]]$grobs[[1]]$children[[2]]$children[[1]]$gp$font,"names") <- "bold"

grid.draw(grob)