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

如何用ggplot2和gglikert组合多条件likert图与计数条形图?

解决方案:结合计数条形图与Likert图的分组可视化

首先加载所需R包:

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

1. 确认数据格式

你的数据构造代码已设置正确的Likert因子水平,若需重新校准因子顺序,可运行:

likert_levels <- c("Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree")
df <- df %>%
  mutate(across(c(val1, val2), ~factor(.x, levels = likert_levels)))

2. 定义组合绘图函数

为避免重复代码,定义函数生成「左侧计数条形图+右侧Likert百分比图」的组合:

plot_combined <- function(data, plot_title) {
  # 左侧:水平计数条形图(统计有效样本量)
  count_plot <- data %>%
    summarize(
      val1 = sum(!is.na(val1)),
      val2 = sum(!is.na(val2))
    ) %>%
    pivot_longer(everything(), names_to = "variable", values_to = "count") %>%
    ggplot(aes(x = count, y = variable)) +
    geom_bar(stat = "identity", fill = "#56B4E9") +
    geom_text(aes(label = count), hjust = 1.2, color = "white") +
    scale_x_reverse(expand = c(0, 0)) +
    labs(x = "有效样本量", y = "") +
    theme_minimal() +
    theme(
      axis.text.y = element_blank(),
      axis.ticks.y = element_blank(),
      panel.grid = element_blank(),
      plot.margin = margin(5, 0, 5, 5)
    )
  
  # 右侧:Likert百分比图
  likert_plot <- data %>%
    select(val1, val2) %>%
    gglikert(
      plot.percent = TRUE,
      fill = "#56B4E9",
      fill.neutral = "#E69F00"
    ) +
    labs(title = plot_title, x = "百分比") +
    theme_minimal() +
    theme(
      plot.title = element_text(hjust = 0.5),
      plot.margin = margin(5, 5, 5, 0)
    )
  
  # 组合图表
  count_plot + likert_plot + plot_layout(widths = c(1, 4))
}

3. 生成并拼接三个条件的图表

分别生成三个筛选条件的组合图,再垂直排列:

# 条件1:var == "Yes"
plot_yes <- plot_combined(filter(df, var == "Yes"), "分组:Yes")

# 条件2:var == "No"
plot_no <- plot_combined(filter(df, var == "No"), "分组:No")

# 条件3:不考虑分组
plot_all <- plot_combined(df, "全部样本")

# 垂直拼接所有图表
final_plot <- plot_yes / plot_no / plot_all +
  plot_annotation(title = "Likert量表分析(含样本量统计)", theme = theme(plot.title = element_text(hjust = 0.5)))

# 输出最终图表
print(final_plot)

核心细节说明

  • 左侧计数图仅统计非NA的有效样本,与右侧Likert图统计范围一致
  • gglikert的plot.percent = TRUE参数直接生成百分比条形图,无需额外计算
  • 使用patchwork的/操作符实现垂直布局,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.16 07:57:21