Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order bars within each factor using ggplot2

Tags:

r

ggplot2

I am creating this "barplot" with ggplot, but I would like to be able to reorrder the bars within each categories so the highest bars are on top. In short having a High to Low bars ordering withing each categories.

Below is my code - Any hints are welcome - Thanks

library("ggplot2")
d <- read.csv('http://db.tt/EOtR3uh', header = F)

d$V4 <- factor(d$V2, levels=d$V2)
base_size <- 11
ggplot(d, aes(d$V4, -log10(d$V3), fill=d$V1)) +
geom_bar(stat="identity") +
coord_flip() +
labs(y = "-log10(Pvalues)",x = "",fill="") +
theme_grey(base_size = base_size) +
scale_x_discrete(expand = c(0, 0))

enter image description here

like image 914
Benoit B. Avatar asked Aug 15 '11 10:08

Benoit B.


1 Answers

Just sort your levels accordingly

d <- read.csv('http://db.tt/EOtR3uh', header = F, stringsAsFactors=FALSE)
lvls <- d$V2[order(d$V1,-d$V3)]
d$V4 <- factor(d$V2, levels=lvls)

ggplot2

like image 131
Ari B. Friedman Avatar answered Nov 15 '22 21:11

Ari B. Friedman