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

如何按Cell.Type分组排序ggplot柱状图?

问题:按Cell.Type分组排序ggplot柱状图

我尝试按分组对ggplot柱状图进行排序,但未能成功。我试过多种方法,仍无法实现目标——当前ggplot按Sample顺序排序,而非Cell.Type顺序。

我的数据集如下:

Cell.Type      Sample   Counts
SRR10162433     hiPSC SRR10162433 27794703
SRR10162434     hiPSC SRR10162434 27077486
SRR10162435     hiPSC SRR10162435 28423798
SRR10162436     hiPSC SRR10162436 26941632
SRR10162445     hiPSC SRR10162445 27393854
SRR10162446     hiPSC SRR10162446 26964857
SRR10162430       TFB SRR10162430 23063031
SRR10162432       TFB SRR10162432 27106366
SRR10162438       TFB SRR10162438 25882727
SRR10162440       TFB SRR10162440 25535387
SRR10162442       TFB SRR10162442 30059135
SRR10162444       TFB SRR10162444 28329032

使用的ggplot代码:

ggplot(data = libSizes, aes(x = Sample, y = Counts/1e6, fill = Cell.Type)) +
  labs(fill = "CellType", x = "Sample", y = "Counts (CPM)") +
  geom_bar(stat = "identity", position = 'dodge') +
  scale_fill_brewer(palette = "Set2") +
  theme_minimal()

期望按Cell.Type分组排序(先hiPSC组,再TFB组),恳请帮助。


解决方法

要实现按Cell.Type分组排序,核心是把Sample列转换成有序因子,让ggplot按照指定顺序绘制。

步骤1:排序数据集并转换因子

先按Cell.Type分组排序,再将Sample转为带固定顺序的因子:

library(dplyr)

# 按Cell.Type和Sample排序,同时把Sample转为因子
libSizes <- libSizes %>%
  arrange(Cell.Type, Sample) %>%
  mutate(Sample = factor(Sample, levels = Sample))

步骤2:重新绘制图表

直接使用处理后的数据集运行原ggplot代码即可:

ggplot(data = libSizes, aes(x = Sample, y = Counts/1e6, fill = Cell.Type)) +
  labs(fill = "CellType", x = "Sample", y = "Counts (CPM)") +
  geom_bar(stat = "identity", position = 'dodge') +
  scale_fill_brewer(palette = "Set2") +
  theme_minimal()

这样所有hiPSC组的样本会先显示,接着是TFB组的样本,完美实现按Cell.Type分组排序的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 05:25:25