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

在R的gglikert中翻转分面行文本并保留顶部分面列标题

实现gglikert分面行文本水平翻转并保留顶部列标题

需求说明:模拟数据与ggstats的likert示例一致,仅group2字段包含长文本,需实现分面行文本水平显示,同时保留顶部的分面列标题。

当前效果(分面行文本垂直显示,长文本占用过多空间):
分面行文本过长的gglikert图

解决方案

通过修改ggplot的主题设置,将分面行的文本旋转为水平,同时确保顶部列标题正常显示:

library(ggstats)
library(dplyr)
library(ggplot2)

# 定义likert等级
likert_levels <- c(
  "Strongly disagree",
  "Disagree",
  "Neither agree nor disagree",
  "Agree",
  "Strongly agree"
)

# 生成基础数据
df <-
  tibble(
    grouping = sample(c("A", "B", "C", "D"), 150, replace = TRUE),
    q1 = sample(likert_levels, 150, replace = TRUE),
    q2 = sample(likert_levels, 150, replace = TRUE, prob = 5:1),
    q3 = sample(likert_levels, 150, replace = TRUE, prob = 1:5),
    q4 = sample(likert_levels, 150, replace = TRUE, prob = 1:5),
    q5 = sample(c(likert_levels, NA), 150, replace = TRUE),
    q6 = sample(likert_levels, 150, replace = TRUE, prob = c(1, 0, 1, 1, 0))
  ) %>%
  mutate(across(-grouping, ~ factor(.x, levels = likert_levels)))

# 添加分组字段
df_group <- df
df_group$group1 <- sample(c("category A", "category B","category C"), 150, replace = TRUE)
df_group$group2 <- sample(c("usa-new york", "usa-san fransisco", "usa-new orleans",
                            "united kingdom-stratford upon avon",
                            "south africa-port elizabeth",
                            "new zealand-upper hutt city"), 150, replace = TRUE)

# 绘制gglikert图并调整分面文本样式
gglikert(df_group,
         q3:q6,
         facet_cols = vars(group1),
         facet_rows = vars(group2),
         labels_size = 3
) +
  scale_x_continuous(
    labels = label_percent_abs(),
    expand = expansion(0, .2)
  ) +
  theme(
    # 将左侧分面行的文本设置为水平显示
    strip.text.y.left = element_text(angle = 0),
    # 确保顶部分面列标题可见(显式声明避免意外隐藏)
    strip.text.x.top = element_text(visible = TRUE)
  )

关键说明

  • strip.text.y.left = element_text(angle = 0):将左侧分面行的文本从默认垂直旋转状态改为水平显示,解决长文本占用过多空间的问题。
  • strip.text.x.top = element_text(visible = TRUE):显式保留顶部分面列标题的显示状态,避免因全局主题设置导致标题意外隐藏。

内容的提问来源于stack exchange,提问作者Homer Jay Simpson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 11:28:17