9

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

Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
Benoit B.
  • 11,854
  • 8
  • 26
  • 29

3 Answers3

4

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

Ari B. Friedman
  • 71,271
  • 35
  • 175
  • 235
  • Good answer, but the way I read it, the OP is asking for ordering within categories and high at the top, so `order(d$v1,-d$v3)` – James Aug 15 '11 at 11:20
  • Indeed - I'd like the order to be within each categories ! – Benoit B. Aug 15 '11 at 11:39
  • I sense deja vu? Hasn't this been asked before and `ordered()` recommended, whereas `factor()` is perfectly fine? It isn't the ordered nature of `ordered()` that is important, it is just getting the correct ordering of the *levels* of the factor. `reorder()` is useful here. Ordering the levels by Group then by response is all that is needed to make factor work. – Gavin Simpson Aug 15 '11 at 15:01
  • 1
    Using `plyr::desc` is slightly more general than `-` because it will also work with factors. – hadley Aug 16 '11 at 18:20
2

Another way to achieve the same objective

require(ggplot2)
d = arrange(d, V1, -V3)                             # arrange d by V1 and -V3
d = transform(d, V2 = factor(V2, as.character(V2))) # order V2 as in d

qplot(V2, -log10(V3), fill = V1, geom = 'bar', data = d) + 
  coord_flip() 
Ramnath
  • 54,439
  • 16
  • 125
  • 152
0

I am answering my question here :

The line to change is

d$V4 <- ordered(d$V2, levels=d$V2[order(d$V1,-d$V3)])

Full code :

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

d$V4 <- ordered(d$V2, levels=d$V2[order(d$V1,-d$V3)])
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

Benoit B.
  • 11,854
  • 8
  • 26
  • 29