4

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"

Jongware
  • 22,200
  • 8
  • 54
  • 100
dulafil
  • 43
  • 1
  • 4

1 Answers1

3
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

Marco Sandri
  • 23,289
  • 7
  • 54
  • 58
  • Unfortunately, I can see that all of the labels are bold. You have all of the labels (`4`, `6`, and `8`) made bold. But as I mentioned I only want `4` to stay bold. Everything else (`6` and `8`) should stay plain! – dulafil Oct 24 '17 at 13:05
  • This is really great. It is amazing how many 'hidden' alleys ggplot has! Thank you for your help. – dulafil Oct 24 '17 at 13:59