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

在R中创建带占比的分组堆叠条形图遇到问题求助

分组堆叠条形图修正方案

原代码问题分析

  1. 位置参数错误:使用position = "fill"会强制将每个条形归一化到100%,无法展示carbon_chain在对应group中的实际占比
  2. 比例计算逻辑偏差:按group计算的prop是功能组在整个组中的占比,结合fill参数后,完全丢失了碳链层级的占比信息
  3. 轴映射错误:将prop作为x轴,无法区分不同carbon_chain的分组

修正后代码

library(tidyverse)
library(scales)

# 读取数据(请替换为你的数据文件路径)
figure1_edit <- read_csv("figure1_edit.csv")

# 数据预处理:计算两层占比
figure4_data <- figure1_edit %>% 
  summarise(N = n(), .by = c(group, carbon_chain, `Functional Group`)) %>%
  mutate(group_total = sum(N), .by = group) %>%
  mutate(chain_total = sum(N), .by = c(group, carbon_chain)) %>%
  mutate(
    # 功能组在对应碳链中的占比
    func_prop = N / chain_total,
    # 最终展示值:碳链在组中的占比 × 功能组在碳链中的占比
    display_value = (chain_total / group_total) * func_prop
  )

# 绘制目标图表
figure4 <- ggplot(figure4_data, aes(x = carbon_chain, y = display_value, fill = `Functional Group`)) +
  geom_bar(stat = "identity", position = "stack") +
  facet_grid(~ group) +
  scale_y_continuous(labels = percent_format(scale = 1)) +
  scale_fill_brewer(palette = "Set3") +
  theme_bw() +
  labs(
    x = "碳链长度",
    y = "在组中的占比",
    fill = "功能基团"
  )

figure4

代码说明

  • 数据处理:通过两层分组计算,先得到carbon_chain在group中的占比,再计算每个Functional Group在对应carbon_chain中的占比,两者相乘后得到的display_value能同时满足“碳链占比”和“功能组堆叠”的需求
  • 绘图参数:使用position = "stack"保留实际比例数值,x轴映射为carbon_chain实现分栏内的碳链分组,facet_grid(~ group)实现按主组划分图表区域

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 03:47:25