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

在R中实现李克特图与年度观测数柱状图的水平维度对齐

实现方法

核心思路

要让两个图的年份维度精准对齐,关键是统一x轴的因子顺序和消除x轴的额外留白,再通过patchwork完成拼接。

步骤与代码

1. 加载所需包

library(tidyverse)
library(gglikert)
library(patchwork)

2. 数据准备(含原始数据)

set.seed(123)
likert_levels <- c(
  "1" = "Very  Dissatisfied",
  "2" = "Dissatisfied",
  "3" = "Neutral",
  "4" = "Satisfied",
  "5" = "Very  Satisfied")
df = data.frame(
  year = sample(c(2023, 2022, 2020, 2018), 50, replace = TRUE),
  A = sample(likert_levels, 50, replace = TRUE),
  B = sample(likert_levels, 50, replace = TRUE),
  C = sample(likert_levels, 50, replace = TRUE))%>%
  mutate(across(everything(),as.factor))%>%
  as_tibble()%>%
  mutate(across(-year, ~ factor(.x, levels = likert_levels)))

# 计算各年度观测数,同时统一年份因子顺序(和李克特图完全一致)
year_counts <- df %>%
  count(year, name = "n") %>%
  mutate(year = factor(year, levels = c("2023", "2022", "2020", "2018")))

3. 绘制柱状图(对齐x轴设置)

bar_plot <- ggplot(year_counts, aes(x = year, y = n)) +
  geom_col(fill = "#619CFF") +
  labs(y = "观测数量", x = "") + # 隐藏x轴标签,避免和下方李克特图重复
  theme_minimal() +
  scale_x_discrete(expand = c(0, 0)) + # 消除x轴两侧默认留白
  scale_y_continuous(expand = expansion(mult = c(0, 0.05))) # 顶部留少量空间防止柱子顶到边界

4. 绘制李克特图(匹配x轴参数)

likert_plot <- df %>%
  mutate(id = row_number()) %>%
  pivot_longer(-c(id, year), names_to = "group") %>%
  pivot_wider(names_from = year) %>%
  gglikert(c(`2023`, `2022`, `2020`, `2018`), 
           facet_rows = vars(group)) +
  scale_x_discrete(expand = c(0, 0)) + # 和柱状图保持一致,消除x轴留白
  labs(x = "年份")

5. 拼接两个图

# 垂直拼接,设置高度比例让布局更协调
bar_plot / likert_plot +
  plot_layout(heights = c(1, 3)) +
  plot_annotation(title = "年度满意度分布与观测数量")

关键注意点

  • 两个图的year因子顺序必须完全相同,否则x轴刻度会错位
  • 统一设置scale_x_discrete(expand = c(0, 0))是精准对齐的核心,消除了ggplot默认的x轴留白
  • 通过plot_layout调整高度比例,让柱状图和李克特图的视觉占比更合理

内容的提问来源于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.15 23:13:10