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

如何在R的ggplot中基于type与group双变量实现分组条形图?

在R的ggplot中实现带group分组的填充条形图

你目前已实现按type(Tax/Income/VAT)分面的填充条形图,但希望在图表底部加入group(A/B)的分组标识,以下是针对性修改方案:

现有代码与数据

当前使用代码

plot <- ggplot(data=df, aes(x=Person, y=Amount, fill=FIAT ))+
  geom_bar(aes(), stat="identity", position="fill")+ 
  facet_grid(~type, scales="free_x")

数据结构

df.new <- structure(list(Person = c("Jon", "Bill", "Maria", "Ben", "Tina", 
"lisa"), Amount = c(23, 41, 32, 58, 26, 54), type = c("Tax", 
"Tax", "VAT", "Income", "Tax", "Income"), group = c("A", "B", 
"B", "A", "B", "A"), FIAT = c("BTC", "GBP", "BTC", "EURO", "USD", 
"USD")), row.names = c(NA, 6L), class = "data.frame")

解决方案

根据你"底部带有group分组"的需求,提供三种可行方案:

方案1:用分面同时展示group与type

将group加入分面参数,让group作为独立的行/列分面,清晰区分分组:

library(ggplot2)

ggplot(data=df.new, aes(x=Person, y=Amount, fill=FIAT)) +
  geom_bar(stat="identity", position="fill") +
  facet_grid(group ~ type, scales="free_x") +
  theme_bw()

方案2:将group与Person绑定为x轴标签

通过interaction()把group和Person合并为x轴项,直接在x轴显示分组关系:

ggplot(data=df.new, aes(x=interaction(group, Person, sep = " - "), y=Amount, fill=FIAT)) +
  geom_bar(stat="identity", position="fill") +
  facet_grid(~type, scales="free_x") +
  labs(x="Person (所属Group)") +
  theme(axis.text.x = element_text(angle=45, hjust=1))

方案3:手动添加group分组标签与分隔线

如果不想修改分面或x轴结构,可手动在x轴底部添加分组标识:

library(dplyr)

# 先计算每个group对应的Person位置
group_pos <- df.new %>%
  group_by(group) %>%
  summarize(min_pos = min(as.integer(factor(Person))),
            max_pos = max(as.integer(factor(Person))))

ggplot(data=df.new, aes(x=factor(Person), y=Amount, fill=FIAT)) +
  geom_bar(stat="identity", position="fill") +
  facet_grid(~type, scales="free_x") +
  # 添加分组分隔线
  annotate("segment", x=group_pos$max_pos + 0.5, xend=group_pos$max_pos + 0.5,
           y=-0.05, yend=0, color="black") +
  # 添加分组标签
  annotate("text", x=(group_pos$min_pos + group_pos$max_pos)/2,
           y=-0.1, label=group_pos$group) +
  # 扩大底部边距容纳标签
  theme(axis.text.x = element_text(angle=45, hjust=1),
        plot.margin = margin(10,10,30,10))

方案说明

  • 方案1适合需要将group作为独立模块展示的场景;
  • 方案2适合在同一分面内直观区分每个Person所属的group;
  • 方案3适合保持原有分面结构,仅在x轴底部补充分组标识的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 03:55:37