tags:

views:

114

answers:

3

I have a data.frame, that is sorted from highest to lowest. For example:

x <- structure(list(variable = structure(c(10L, 6L, 3L, 4L, 2L, 8L, 
9L, 5L, 1L, 7L), .Label = c("a", "b", "c", "d", "e", "f", "g", 
"h", "i", "j"), class = c("ordered", "factor")), value = c(0.990683229813665, 
0.975155279503106, 0.928571428571429, 0.807453416149068, 0.717391304347826, 
0.388198757763975, 0.357142857142857, 0.201863354037267, 0.173913043478261, 
0.0496894409937888)), .Names = c("variable", "value"), row.names = c(10L, 
6L, 3L, 4L, 2L, 8L, 9L, 5L, 1L, 7L), class = "data.frame")

ggplot(x, aes(x=variable,y=value)) + geom_bar() + 
+ scale_y_continuous("",formatter="percent") + coord_flip() 

Now, the data is nice and sorted, but when I plot, it comes out sorted by factor. It's annoying, how do I fix it?

+1  A: 

You need to make the x-factor into an ordered factor with the ordering you want, e.g

x <- data.frame("variable"=letters[1:5], "value"=rnorm(5)) ## example data
x <- x[with(x,order(-value)), ] ## Sorting
x$variable <- ordered(x$variable, levels=levels(x$variable)[unclass(x$variable)])

ggplot(x, aes(x=variable,y=value)) + geom_bar() +
   scale_y_continuous("",formatter="percent") + coord_flip()

I don't know any better way to do the ordering operation. What I have there will only work if there are no duplicate levels for x$variable.

Zack
This works for the example I have provided, but it doesn't seem to translate for my actual problem.
Brandon Bertelsen
I've changed the example to provide actual data that I'm working with
Brandon Bertelsen
Works perfectly when I try it...
Zack
It doesn't need to be an _ordered_ factor - it just needs to be a factor with the right order.
hadley
+2  A: 

Here are a couple of ways.

The first will order things based on the order seen in the data frame:

x$variable <- factor(x$variable, levels=unique(as.character(x$variable)) )

The second orders the levels based on another variable (value in this case):

x <- transform(x, variable=reorder(variable, -value) ) 
Greg Snow
The second one consitently provided the result I was looking for without the "-".
Brandon Bertelsen
+1  A: 

Hi: Is this what you were looking for?

g <- ggplot(x, aes(x=reorder(variable, value) ,y=value)) g + geom_bar() + scale_y_continuous(formatter="percent") + coord_flip()

HTH, Dennis

djmuseR