R ggplot在"barplot-like"图中排序

Ben*_* B. 10 sorting r ggplot2

这是我的代码:

ggplot(tmp, aes(x=tmp$V2, y=-log10(tmp$V3), fill=tmp$V1)) +
geom_bar(stat="identity") +
coord_flip()
Run Code Online (Sandbox Code Playgroud)

现在我想创建与上面相同的图,但是每个"组"中的值都被排序.看起来像这样的东西.

Bra*_*sen 9

ggplot(df, aes(reorder(x,y),y)) + geom_bar()
Run Code Online (Sandbox Code Playgroud)

您正在寻找的部分是重新排序(x,y).但是如果你能告诉我们你当前的ggplot()调用,我们可能会更具体,因为reorder()不是唯一的方法.

对于这种类型的排序,您可能需要使用relevel(),但这取决于您的数据.

您还可以在data.frame()中添加另一个列,它将作为一个排序变量,手动或自动,并基于您的reorder()调用.


koh*_*ske 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()
Run Code Online (Sandbox Code Playgroud)

这里是进一步的信息:http://kohske.wordpress.com/2010/12/29/faq-how-to-order-the-factor-variables-in-ggplot2/


小智 5

假设 Ben 提供的数据在一个名为 的 CSV 文件中data.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()
Run Code Online (Sandbox Code Playgroud)

与 kohske 的答案相比,此方法更通用一些,并且不需要对 CSV 进行排序(更改 CSV 文件中的行顺序仍将重现正确的图形)。