首页 文章

在geom_bar ggplot2中重新排序条形图

提问于
浏览
84

我正在尝试制作一个条形图,其中的情节从 miRNA 订购,最高 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")

2 回答

  • 164

    您的代码工作正常,但条形图从低到高排序 . 当您想要从高到低排序时,您必须在 value 之前添加 - 符号:

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

    这使:

    enter image description here


    Used data:

    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"))
    
  • -1

    您可以使用 reorder() 函数沿x轴重新排序变量 . 但是,有时ggplot不会影响结果,请尝试暂时删除或静音其他功能,然后逐个添加它们 .

    ggplot(aes(x=reorder(myx, -myy), y=myy), data=mydf) + geom_bar(stat="identity")

相关问题