这是我的代码:
ggplot(tmp, aes(x=tmp$V2, y=-log10(tmp$V3), fill=tmp$V1)) +
geom_bar(stat="identity") +
coord_flip()
现在我想创建与上面相同的图,但是每个“组”中的值都被排序。看起来像这样的东西。
答案 0 :(得分:9)
ggplot(df, aes(reorder(x,y),y)) + geom_bar()
您正在寻找的部分是重新排序(x,y)。但是如果你能告诉我们你当前的ggplot()调用,我们可能会更具体,因为reorder()不是唯一的方法。
对于这种类型的排序,您可能需要使用relevel(),但这取决于您的数据。
您还可以在data.frame()中添加另一列,作为排序变量,手动或自动,并将reorder()调用基于此。
答案 1 :(得分:9)
您可以通过将变量转换为因子来对其进行排序。
> head(d)
V1 V2 V3
1 GO Biological Process regulation of lipid metabolic process 1.87e-35
2 GO Biological Process acute inflammatory response 3.21e-37
3 GO Biological Process response to insulin stimulus 1.05e-38
4 GO Biological Process steroid metabolic process 4.19e-39
5 GO Biological Process cholesterol metabolic process 1.19e-40
6 GO Biological Process cellular response to chemical stimulus 5.87e-42
> d$V4 <- factor(d$V2, levels=d$V2) # convert V2 into factor
> head(d)
V1 V2 V3 V4
1 GO Biological Process regulation of lipid metabolic process 1.87e-35 regulation of lipid metabolic process
2 GO Biological Process acute inflammatory response 3.21e-37 acute inflammatory response
3 GO Biological Process response to insulin stimulus 1.05e-38 response to insulin stimulus
4 GO Biological Process steroid metabolic process 4.19e-39 steroid metabolic process
5 GO Biological Process cholesterol metabolic process 1.19e-40 cholesterol metabolic process
6 GO Biological Process cellular response to chemical stimulus 5.87e-42 cellular response to chemical stimulus
> # plot
> ggplot(d, aes(V4, -log10(V3), fill=V1)) + geom_bar() + coord_flip()
这里有更多信息:http://kohske.wordpress.com/2010/12/29/faq-how-to-order-the-factor-variables-in-ggplot2/
答案 2 :(得分:4)
假设Ben提供的数据位于名为data.csv
的CSV文件中:
d <- read.csv('data.csv', header = F)
d$V2 <- factor(d$V2, levels=d[order(d$V1, -d$V3), ]$V2) #reorder by grp/value
ggplot(d, aes(x=V2, y=-log10(V3), fill=V1)) + geom_bar() + coord_flip()
与kohske的答案相比,此方法更为通用,并且不需要对CSV进行排序(更改CSV文件中行的顺序仍将重现正确的图形)。