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

如何在ggplot2的Likert图中仅展示左右合计与中间类别百分比

解决方法

方法一:先合并Likert类别(更推荐)

先给原始数据框df做预处理,把原来的5级Likert选项合并成你需要的3个类别,再用合并后的数据绘图,这是最直观、不容易出问题的方式。

步骤1:合并类别

假设你的Likert响应列名为response,执行以下代码生成合并后的新列:

library(dplyr)

df <- df %>%
  mutate(
    response_combined = case_when(
      response %in% c("Strongly disagree", "Disagree") ~ "不同意(合计)",
      response == "Neither agree nor disagree" ~ "既不同意也不反对",
      response %in% c("Agree", "Strongly agree") ~ "同意(合计)"
    )
  )

记得根据你实际的列名、类别文本调整case_when里的内容。

步骤2:用合并后的数据绘制Likert图

直接调用ggstats的绘图函数,传入合并后的列即可:

library(ggplot2)
library(ggstats)

ggplot(df, aes(y = 你的分组列名, fill = response_combined)) +
  geom_likert() +
  # 可选:给合并后的类别配置对应颜色
  scale_fill_manual(
    values = c("不同意(合计)" = "#d73027", 
               "既不同意也不反对" = "#fdae61", 
               "同意(合计)" = "#1a9850")
  ) +
  labs(title = "合并后的Likert分布", x = "百分比", y = "分组")

把你的分组列名替换为你实际用来分组的列(比如不同问题、不同受访者群体等)。

方法二:不修改原始数据,调整绘图标签和图例

如果必须保留原始数据结构,可以通过自定义标签和合并图例的方式,隐藏单独类别的百分比,只显示合计值。这种方法相对繁琐,适合特定场景:

ggplot(df, aes(y = 你的分组列名, fill = response)) +
  geom_likert(
    label = function(x) {
      # 仅显示合计和中立的百分比,其他类别留空
      case_when(
        x$response == "Disagree" ~ paste0(round(x$pct_total, 1), "%"),
        x$response == "Agree" ~ paste0(round(x$pct_total, 1), "%"),
        x$response == "Neither agree nor disagree" ~ paste0(round(x$pct_total, 1), "%"),
        TRUE ~ ""
      )
    }
  ) +
  # 将同组类别设置为相同颜色
  scale_fill_manual(
    values = c("Strongly disagree" = "#d73027", "Disagree" = "#d73027",
               "Neither agree nor disagree" = "#fdae61",
               "Agree" = "#1a9850", "Strongly agree" = "#1a9850"),
    labels = c("不同意(合计)", "不同意(合计)",
               "既不同意也不反对",
               "同意(合计)", "同意(合计)")
  ) +
  # 调整图例,仅显示3个合并后的项
  guides(fill = guide_legend(
    override.aes = list(fill = c("#d73027", "#fdae61", "#1a9850")),
    label = c("不同意(合计)", "既不同意也不反对", "同意(合计)")
  ))

内容的提问来源于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 21:03:29