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

如何在ggplot中按ploidy 4占比降序排序堆叠比例柱状图X轴

解决方案

先处理数据中的样本名称一致性问题,再按需求排序X轴,最终绘制优化后的堆叠比例柱状图:

步骤1:数据预处理与排序

library(dplyr)
library(ggplot2)

# 统一样本名称大小写(避免s5和S5被识别为不同样本)
df_clean <- df %>%
  mutate(sample = tolower(sample))

# 提取每个样本中ploidy=4的频率,无该类别的样本补0
sample_ploidy4 <- df_clean %>%
  filter(ploidy == 4) %>%
  select(sample, freq_ploidy4 = freq)

# 生成样本排序规则:先按ploidy4占比降序,无该类别的按字母升序
sample_order <- df_clean %>%
  distinct(sample) %>%
  left_join(sample_ploidy4, by = "sample") %>%
  mutate(freq_ploidy4 = replace_na(freq_ploidy4, 0)) %>%
  arrange(desc(freq_ploidy4), sample) %>%
  pull(sample)

# 将样本列转为指定顺序的因子,确保绘图时X轴顺序正确
df_clean <- df_clean %>%
  mutate(sample = factor(sample, levels = sample_order))

步骤2:绘制堆叠比例柱状图

ggplot(df_clean, aes(x = sample, y = freq, fill = factor(ploidy))) +
  geom_col(position = "stack") +
  labs(x = "样本", y = "频率", fill = "倍性") +
  theme_bw()

关键说明

  • tolower(sample) 统一样本名称格式,避免大小写差异导致的分组错误。
  • 用replace_na补全无ploidy4样本的频率为0,确保排序逻辑覆盖所有样本。
  • 通过arrange实现核心排序规则:优先按ploidy4占比降序排列,占比为0的样本按字母顺序升序排列。
  • 将sample转为带指定levels的因子,是保证X轴顺序符合要求的核心操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 08:22:40