r - ggplot : Using strip. text.x (element_text) 用于仅制作刻面轴标签 "bold"的一个元素

标签 r ggplot2 font-face facet

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

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 ”为 粗体 .

enter image description here

使用 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)

enter image description here

关于r - ggplot : Using strip. text.x (element_text) 用于仅制作刻面轴标签 "bold"的一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46905774/

相关文章:

r - ggplot几何点,修改文本

R ggplot2 : colouring step plot depending on value

css - 字体间歇性加载失败?

r - `sp::over()` 相当于 `terra`

r - 更改数据框列表中的名称

r - R 的 ggplot2 中 geom_point 中数据点的垂直线

fonts - Safari 用户安装的字体不呈现

html - 什么字体大小 :30; be equivalent to in px?

java - 使用 JRI 从 JSP 动态绘制 R 图

r - 在ggplot中绘制两个图表