按值重新排列 geom_bar ggplot2中的条

我试图做一个条形图,其中的情节是从最高的 value到最低的 miRNA排序。为什么我的代码不工作?

> head(corr.m)


miRNA         variable value
1    mmu-miR-532-3p      pos     7
2    mmu-miR-1983        pos    75
3    mmu-miR-301a-3p     pos    70
4    mmu-miR-96-5p       pos     5
5    mmu-miR-139-5p      pos    10
6    mmu-miR-5097        pos    47


ggplot(corr.m, aes(x=reorder(miRNA, value), y=value, fill=variable)) +
geom_bar(stat="identity")
230142 次浏览

您的代码工作得很好,除了条形图是从低到高排列的。当你想从高到低订购酒吧时,你必须在 value之前添加一个 -标志:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) +
geom_bar(stat = "identity")

它给出了:

enter image description here


使用数据:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
value = c(7L, 75L, 70L, 5L, 10L, 47L)),
class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

除了@Jaap 的回答,还有另外两种方式来安排剧情:

1: 使用 desc参数表示值:

ggplot(corr.m, aes(x = reorder(miRNA, desc(value)), y = value, fill = variable)) +
geom_bar(stat = "identity")

2: 通过调整 miRNA 因子的水平,省略 reorder论点:

corr.m %>%
arrange(desc(value)) %>%
mutate(miRNA = factor(miRNA, levels = unique(miRNA))) %>%
ggplot(aes(x = miRNA, y = value, fill = variable)) +
geom_bar(stat = "identity")

另一个选项是创建一个 factor变量,其中因子 levels根据您的值变量按递减顺序排列。

减少 = 真实

library(ggplot2)
# Create factor column with decreasing order TRUE
corr.m$miRNA <- factor(corr.m$miRNA, levels = corr.m$miRNA[order(corr.m$value, decreasing = TRUE)])


ggplot(corr.m, aes(x=miRNA, y=value, fill=variable)) +
geom_bar(stat="identity")

创建于2022-08-19与 Reprex v2.0.2

减少 = 假

library(ggplot2)
# Create factor column with decreasing order FALSE
corr.m$miRNA <- factor(corr.m$miRNA, levels = corr.m$miRNA[order(corr.m$value, decreasing = FALSE)])


ggplot(corr.m, aes(x=miRNA, y=value, fill=variable)) +
geom_bar(stat="identity")

创建于2022-08-19与 Reprex v2.0.2