Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
933 views
in Technique[技术] by (71.8m points)

sorting - R ggplot ordering bars in "barplot-like " plot

This is my code:

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

Now I would like to create the same plot as above but where the values within each "groups" are sorted. Something that will look like this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can order the variable by converting it into factor.

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

here is further information: http://kohske.wordpress.com/2010/12/29/faq-how-to-order-the-factor-variables-in-ggplot2/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...