Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: sorting a plot

Tags:

r

ggplot2

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(stat="identity") +   scale_y_continuous("",label=scales::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?

like image 493
Brandon Bertelsen Avatar asked Sep 19 '10 01:09

Brandon Bertelsen


People also ask

How do I rearrange the order of a bar chart in R?

To reorder bars manually, you have to pass stat=”identity” in the geom_bar() function.

How do you plot a graph in descending order in R?

Rearranging Results in Basic R Then draw the bar graph of the new object. If you want the bar graph to go in descending order, put a negative sign on the target vector and rename the object. Then draw the bar graph of the new object.

How do I reorder data in R?

To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order.

How do I reorder my legend ggplot2?

You can use the following syntax to change the order of the items in a ggplot2 legend: scale_fill_discrete(breaks=c('item4', 'item2', 'item1', 'item3', ...)


1 Answers

This seems to be what you're looking for:

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

The reorder() function will reorder your x axis items according to the value of variable.

like image 142
djmuseR Avatar answered Sep 21 '22 01:09

djmuseR