按值重新排序 geom_bar ggplot2 中的条形图 [英] Reorder bars in geom_bar ggplot2 by value

查看:19
本文介绍了按值重新排序 geom_bar ggplot2 中的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个条形图,其中该图的顺序是从 miRNA 具有最高 valuemiRNA 与最低.为什么我的代码不起作用?

I am trying to make a bar-plot where the plot is ordered from the miRNA with the highest value to the miRNA with the lowest. Why does my code not work?

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

推荐答案

您的代码工作正常,除了条形图是从低到高排序的.当您想按从高到低的顺序排列时,您必须在 value 之前添加一个 - 符号:

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

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

给出:

使用的数据:

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

这篇关于按值重新排序 geom_bar ggplot2 中的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆