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

使用gglikert在R中绘制带百分比的Likert图并按指定规则排序

解决方案

1. 数据预处理:按低等级总和排序国家

首先计算每个国家的Strongly Disagree + Disagree总和,以此为依据对国家降序排序,并将Country列转换为因子(固定排序顺序,确保绘图时Y轴符合要求)。

# 加载依赖包
library(ggstats)
library(ggplot2)
library(dplyr)
library(tidyr)

# 示例数据(替换为你的实际数据框df)
df <- data.frame(
  Country = c("USA", "China", "Germany", "Japan"),
  `Strongly Disagree` = c(15, 8, 20, 10),
  Disagree = c(20, 12, 25, 15),
  `So So` = c(30, 40, 25, 30),
  Agree = c(25, 28, 20, 35),
  `Strongly Agree` = c(10, 12, 10, 10)
)

# 计算低等级总和并排序国家
df_sorted <- df %>%
  mutate(low_total = `Strongly Disagree` + Disagree) %>%
  arrange(desc(low_total)) %>%  # 按低等级总和降序排列
  mutate(Country = factor(Country, levels = Country)) %>%  # 固定国家顺序为排序后的结果
  select(-low_total)  # 移除辅助计算列

2. 使用ggstats::gglikert绘制Likert图

gglikert专门用于Likert数据可视化,无需手动转换数据格式,直接传入排序后的数据集即可:

gglikert(df_sorted, y = Country) +
  labs(
    x = "百分比",
    y = "国家",
    title = "各国Likert等级分布(按低等级总和降序)",
    fill = "Likert等级"
  ) +
  theme_minimal()

3. 使用ggplot2手动绘制Likert图

如果偏好原生ggplot2,可将数据转为长格式后绘制,支持两种常见样式:

样式1:横向堆叠条形图

# 转换为长格式
df_long <- df_sorted %>%
  pivot_longer(cols = -Country, names_to = "Likert", values_to = "Percentage") %>%
  mutate(Likert = factor(Likert, levels = c("Strongly Disagree", "Disagree", "So So", "Agree", "Strongly Agree")))

# 绘制堆叠条形图
ggplot(df_long, aes(x = Percentage, y = Country, fill = Likert)) +
  geom_col(position = "stack") +
  labs(
    x = "百分比",
    y = "国家",
    fill = "Likert等级",
    title = "各国Likert等级分布(按低等级总和降序)"
  ) +
  theme_minimal()

样式2:对称Likert图(负面左、正面右)

df_long <- df_sorted %>%
  pivot_longer(cols = -Country, names_to = "Likert", values_to = "Percentage") %>%
  mutate(
    Likert = factor(Likert, levels = c("Strongly Disagree", "Disagree", "So So", "Agree", "Strongly Agree")),
    # 调整百分比:负面设为负值,正面设为正值,中立居中
    adjusted_perc = case_when(
      Likert %in% c("Strongly Disagree", "Disagree") ~ -Percentage,
      Likert == "So So" ~ Percentage / 2,
      TRUE ~ Percentage
    )
  )

ggplot(df_long, aes(x = adjusted_perc, y = Country, fill = Likert)) +
  geom_col() +
  geom_vline(xintercept = 0, color = "black", linetype = "dashed") +
  scale_x_continuous(breaks = seq(-100, 100, 25), labels = abs(seq(-100, 100, 25))) +
  labs(
    x = "百分比",
    y = "国家",
    fill = "Likert等级",
    title = "各国Likert等级分布(按低等级总和降序)"
  ) +
  theme_minimal()

关键说明

  • 排序核心是将Country转为因子并指定排序后的水平,确保绘图工具严格按照该顺序渲染Y轴。
  • gglikert会自动识别Likert等级顺序并优化可视化效果,是最简便的方案。
  • 若使用ggplot2,需手动处理数据格式和可视化逻辑,灵活性更高。

内容的提问来源于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.24 03:05:16