ggplot:使用strip.text.x(element_text)只生成构面轴标签的一个元素"粗体"

时间:2017-10-24 08:35:53

标签: r ggplot2 font-face facet

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

element_text

因此,在这里,我只想要标签" 4 "在顶部是粗体

enter image description here

使用Grob

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

NULL

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
  

getGrob出错(elem,&#34; strip.text.x.text&#34;,grep = TRUE):它是   仅适用于从#34; gTree&#34;

获取孩子

1 个答案:

答案 0 :(得分:1)

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