How to order breaks with ggplot / geom_bar

I have data.frame with entries like:

    variable importance order
 1 foo 0.06977263 1
 2 bar 0.05532474 2
 3 baz 0.03589902 3
 4 alpha 0.03552195 4
 5 beta 0.03489081 5
        ...

When plotting the chart above, with breaks = variable, I would like the order to be preserved, and not placed in alphabetical order.

I process with:

 
 ggplot (data, aes (x = variable, weight = importance, fill = variable)) + 
     geom_bar () + 
     coord_flip () + opts (legend.position = 'none')

However, the order of the variable names is alphabetical, not the order in the data frame. I saw a message about using "order" in aes, but it seems to have no effect.

I am looking to have an interrupt order in a row with an order column.

It seems there is a similar question How to change the order of the discrete scale x in ggplot , but, frankly, did not understand the answer in this context.

+3
r ggplot2
Oct 22 '10 at 20:22
source share
4 answers

Try:

data$variable <- factor(data$variable, levels=levels(data$variable)[order(-data$order)]) 

From: ggplot2 sorting plot Part II

+6
Oct 22 '10 at 20:45
source share

Even shorter and clearer:

 data$Variable <- reorder(data$Variable, data$order) 
+4
Feb 15 2018-11-15T00:
source share

Another solution is to build the order and then change the labels after the fact:

 df <- data.frame(variable=letters[c(3,3,2,5,1)], importance=rnorm(5), order=1:5) p <- qplot(x=order, weight=importance, fill=variable, data=df, geom="bar") + scale_x_continuous("", breaks=1:5, labels=df$variable) + coord_flip() + opts(legend.position='none') 
+2
Oct 22 2018-10-22
source share

The shot is in the dark, but there might be something like this:

 data$variable <- factor(data$variable, levels=data$variable) 
+1
Oct 22 '10 at 20:50
source share



All Articles