Search code examples
rggplot2font-facefacet

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


I want to use bold face only on the first element of my top x axis label (in the facet panel). This can be done using the element_text function. However, when I do the following, all elements in the facet are turned to "bold", while I only want the first one to be 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")))

Therefore, in here, I only want the label "4" at the top to be bold.

enter image description here

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


Solution

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

    enter image description here