Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R ggplot ordering bars in "barplot-like " plot

Tags:

sorting

r

ggplot2

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.

like image 747
Benoit B. Avatar asked Aug 01 '11 16:08

Benoit B.


1 Answers

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

like image 109
Dario Buttari Avatar answered Oct 07 '22 20:10

Dario Buttari