Reputation: 2455
I have this R code code to generate the following barplot:
d <- data.frame(case = c(1,2,3,4),
var=c('foo', 'foo', 'foo', 'foo','bar', 'bar', 'bar', 'bar'),
val=c(9,2,2,4,6,1,2,3))
d$var <- as.factor(d$var)
d$case <- as.factor(d$case)
ggplot(d, aes(x = case, y = val, fill = var)) + scale_x_discrete() + geom_bar(position="dodge")
How can I sort the bars by the value of 'bar'?
Disclaimer: this might be a duplicate of https://stackoverflow.com/questions/10746342/sorting-ggplot2-box-plot-by-2-columns but this was not answered, so...
Upvotes: 4
Views: 8011
Reputation: 118779
Use order
to get the columns ordered by values for bar
and replicate it in foo
as well. Then use this column for x
.
d$case <- match(d$val[d$var == "bar"], sort(d$val[d$var == "bar"]))
d$case <- factor(d$case, levels=1:4)
# now use this:
ggplot(d, aes(x = case, y = val, fill = var)) +
geom_bar(position="dodge", stat="identity")
(or equivalently)
ggplot(d, aes( x= order, fill = var)) + geom_bar(aes(weights=val), position="dodge")
Upvotes: 5