3

I have a 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 above, with the breaks = variable, I would like for the order to be preserved, rather than placed in alphabetical order.

I am rendering with:

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

However, the ordering of the variable names is alphabetical, and not the order within the data frame. I had seen a post about using "order" in aes, but appears to have no effect.

I am looking to have a breaks ordering in-line with the "order" column.

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

Community
  • 1
  • 1
Jonathan Shore
  • 880
  • 2
  • 8
  • 21

4 Answers4

7

Try:

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

From: ggplot2 sorting a plot Part II

Community
  • 1
  • 1
Brandon Bertelsen
  • 43,807
  • 34
  • 160
  • 255
4

Even shorter and easier to understand:

data$Variable <- reorder(data$Variable, data$order)
Xavier Guardiola
  • 2,699
  • 3
  • 19
  • 11
2

Another solution is to plot 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')
Shane
  • 98,550
  • 35
  • 224
  • 217
  • Thanks. This solves it. Wish there was a built-in approach with an order attribute, but I suppose would not be a widely used feature. – Jonathan Shore Oct 22 '10 at 23:25
1

A shot in the dark, but maybe something like this:

data$variable <- factor(data$variable, levels=data$variable)
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418