tags:

views:

72

answers:

2

I am making a dodged bar chart using ggplot with discrete x scale, the x axis are now arranged in alphabetical order, but I need to rearrange it so that it is ordered by the value of the y-axis (i.e., the tallest bar will be positioned on the left), I tried order or sort, but result in sort the x-axis, but not the bars respectively. What have I done wrong?

Thanks!

+1  A: 

Try manually setting the levels of the factor on the x-axis. For example:

# Automatic levels
ggplot(mtcars, aes(factor(cyl))) + geom_bar()    

# Manual levels
cyl_table <- table(mtcars$cyl)
cyl_levels <- names(cyl_table)[order(cyl_table)]
mtcars$cyl2 <- factor(mtcars$cyl, levels = cyl_levels) 
ggplot(mtcars, aes(cyl2)) + geom_bar()
Richie Cotton
A: 

You can use reorder:

qplot(reorder(factor(cyl),factor(cyl),length),data=mtcars,geom="bar")

Edit:

To have the tallest bar at the left, you have to use a bit of a kludge:

qplot(reorder(factor(cyl),factor(cyl),function(x) length(x)*-1),
   data=mtcars,geom="bar")

I would expect this to also have negative heights, but it doesn't, so it works!

James