Reputation: 12054
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))
Upvotes: 9
Views: 2139
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)
Upvotes: 4
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
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))
Upvotes: 0