Benoit B.
Benoit B.

Reputation: 12054

Order bars within each factor using 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

Upvotes: 9

Views: 2139

Answers (3)

Ari B. Friedman
Ari B. Friedman

Reputation: 72769

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

Upvotes: 4

Ramnath
Ramnath

Reputation: 55715

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

Upvotes: 2

Benoit B.
Benoit B.

Reputation: 12054

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

Upvotes: 0

Related Questions