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

在R中使用ggplot绘制三重分组柱状图出现问题求助

解决ggplot三重柱状图绘制问题

你的代码问题出在用宽数据直接叠加多个geom_bar,这种方式会让ggplot无法正确识别分组关系,导致柱子位置混乱。ggplot更适合处理长格式数据(tidy data),正确的做法是先把你的宽数据转换成长数据,再一次性绘制分组柱状图。

步骤1:转换数据格式

使用tidyr::pivot_longer把你的宽数据(每个变量一列)转成长数据(变量名和对应值各一列),同时给变量替换成你需要的显示标签:

# 先加载必要的包
library(tidyverse)

# 转换数据格式
data_long <- data %>%
  pivot_longer(
    cols = c(x48, x49, x54), # 指定要转换的目标列
    names_to = "indicator",
    values_to = "value",
    # 替换变量名为易读的标签
    names_transform = list(indicator = ~case_when(
      .x == "x48" ~ "Rent price for a 1 room apartment in the center",
      .x == "x49" ~ "Rent price for a 1 room apartment outside the center",
      .x == "x54" ~ "Average monthly salary"
    ))
  )

步骤2:绘制正确的三重柱状图

用转换后的长数据绘图,只需要调用一次geom_bar,通过fill映射分组变量,设置position = "dodge"让分组柱子并排显示:

ggplot(data_long, aes(x = country, y = value, fill = indicator)) +
  geom_bar(stat = "identity", position = "dodge") +
  # 可选:添加标题和坐标轴标签优化可读性
  labs(
    x = "Country",
    y = "Value",
    fill = "Indicator",
    title = "Rent & Salary Comparison by Country"
  ) +
  # 可选:旋转X轴标签避免重叠
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

关键说明

  • 转成长数据后,每个国家对应3条记录,分别对应三个指标的值,ggplot能自动识别分组关系
  • fill = indicator将不同指标映射到不同颜色,position = "dodge"确保同一国家的三个柱子并排显示,而非堆叠或重叠
  • 之前多次调用geom_bar的写法,会让ggplot无法统一处理分组位置,这就是图表不符合预期的核心原因

内容的提问来源于stack exchange,提问作者walter

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 21:10:20