You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中自定义ggplot2 facet_grid分面标签的字体大小与加粗样式

你需要在原有绘图代码的theme_bw()后追加theme()配置,通过strip.text.x(控制顶部φ分面标签)、strip.text.y(控制右侧sd分面标签)的参数自定义样式:

  • face = "bold"实现粗体效果
  • size参数设置字体大小,可根据需求调整数值

修改后的完整代码如下:

set.seed(1)
df <- data.frame(xx = 1:10, x1 = rnorm(10), x2 = rnorm(10), x3 = rnorm(10), x4 = rnorm(10), x5 = rnorm(10), x6 = rnorm(10), x7 = rnorm(10), x8 = rnorm(10), x9 = rnorm(10), x10 = rnorm(10), x11 = rnorm(10), x12 = rnorm(10))    
library(dplyr)
library(tidyr)
library(ggplot2)

df %>% 
  pivot_longer(-xx) %>% 
  mutate(id = as.numeric(gsub("x", "", name))) %>% 
  arrange(id, xx) %>% 
  select(-id) %>% 
  mutate(sd = rep(rep(c(sd = 1, sd = 3, sd = 5, sd = 10), each = 10), each = 3),
         phi = rep(rep(list(c(0.4, 0.4), c(0.45, 0.45), c(0.35, 0.6)), each = 10), 4)) %>% 
  mutate(sd = factor(sd, levels = sd, labels = paste("sd =", sd)),
         phi = factor(phi, levels = phi, labels = gsub("c", "", paste("\U03D5 =", phi)))) %>%   
  ggplot(aes(x = xx, y = value)) +
  geom_line() + 
  geom_point() +
  scale_y_continuous(expand = c(0.0, 0.00)) +
  labs(x = "Time", y = "Series") +
  facet_grid(sd ~ phi, scales = "free_y") + 
  theme_bw() +
  theme(
    # 自定义顶部phi分面标签样式
    strip.text.x = element_text(face = "bold", size = 12),
    # 自定义右侧sd分面标签样式
    strip.text.y = element_text(face = "bold", size = 12)
  )

如果顶部和右侧标签需要用相同的样式,也可以直接用strip.text统一配置,无需分开设置:

theme(
  strip.text = element_text(face = "bold", size = 12)
)

内容的提问来源于stack exchange,提问作者Daniel James

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 07:54:10