R ggplot ordering bars in "barplot-like " plot

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/


ggplot(df, aes(reorder(x,y),y)) + geom_bar()

The part you're looking for is reorder(x,y). But if you could show us your current ggplot() call we could be more specific as reorder() is not the only method.

For this type of sorting, you may need to use relevel(), but it depends on your data.

You can also add another column to your data.frame() that will act as a sort variable, manually or automatically, and base your reorder() call off of that.


Assuming that the data provided by Ben is in a CSV file called 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()

This method is a little more general compared to the answer from kohske, and does not require the CSV to be sorted (changing the order of the rows in the CSV file will still reproduce the correct graph).

Tags:

Sorting

R

Ggplot2