使用ggplot2对每个因子内的条形进行排序 [英] Order bars within each factor using ggplot2

查看:439
本文介绍了使用ggplot2对每个因子内的条形进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 ggplot 创建这个barplot,但我希望能够对每个类别中的条进行重新排序,以使最高的条位于顶部。简而言之,每个类别都有高到低的酒吧排序。



以下是我的代码 - 欢迎提供任何提示 - 谢谢

  library(ggplot2)
d< - read.csv('http://db.tt/EOtR3uh',header = F)

d $ V4 < - factor(d $ V2,levels = d $ V2)
base_size < - 11
ggplot(d,aes(d $ V4,-log10(d $ V3),fill = d $ V1))+
geom_bar(stat =identity)+
coord_flip()+
labs(y =-log10(Pvalues),x =,fill =)+
theme_grey (base_size = base_size)+
scale_x_discrete(expand = c(0,0))

解决方案

您可以根据需要对您的等级进行排序。

  d < -  read.csv('http://db.tt / EOtR3uh',header = F,stringsAsFactors = FALSE)
lvls <-d $ V2 [order(d $ V1,-d $ V3)]
d $ V4 < - factor(d $ V2 ,levels = lvls)


I am creating this "barplot" with ggplot, but I would like to be able to reorrder the bars within each categories so the highest bars are on top. In short having a High to Low bars ordering withing each categories.

Below is my code - Any hints are welcome - Thanks

library("ggplot2")
d <- read.csv('http://db.tt/EOtR3uh', header = F)

d$V4 <- factor(d$V2, levels=d$V2)
base_size <- 11
ggplot(d, aes(d$V4, -log10(d$V3), fill=d$V1)) +
geom_bar(stat="identity") +
coord_flip() +
labs(y = "-log10(Pvalues)",x = "",fill="") +
theme_grey(base_size = base_size) +
scale_x_discrete(expand = c(0, 0))

解决方案

Just sort your levels accordingly

d <- read.csv('http://db.tt/EOtR3uh', header = F, stringsAsFactors=FALSE)
lvls <- d$V2[order(d$V1,-d$V3)]
d$V4 <- factor(d$V2, levels=lvls)

这篇关于使用ggplot2对每个因子内的条形进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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