0

Possible Duplicate:
Order Bars in ggplot2 bar graph

I have the following data frame (df) in R that I wish to create a box plot for:

    Entity  Mean    Min Q1      Med     Q3      Max
1   ABCD    88.65   0   75.0    100.0   100.0   100
2   BAAF    88.73   0   91.0    100.0   100.0   100
3   BCC4    70.26   0   20.0    100.0   100.0   100
4   C9FE    77.98   0   66.0    86.0    100.0   100
5   D3AA    71.97   0   51.0    82.0    100.0   100   

The code I use is as follows:

Lplot <- ggplot(df, aes(Entity, ymin=Min, lower=Q1, middle=Med, upper=Q3, ymax=Max,
         fill=Mean))
mth <- theme(axis.text.x = element_text(angle = 90, hjust = 1))
bplot <- geom_boxplot(stat="identity")
sfg <- scale_fill_gradient("Mean", low="green", high="red")

Lplot + mth + sfg + bplot

This graphs the data frame with Entity on the x-axis and the appropriate quantiles on the y-axis. However, I would like to sort the plots by Mean. I can achieve this effect by replacing aes(Entity,... with aes(factor(Mean),... but then the mean values appear on the x-axis when I still want the Entity names there.

Essentially what I am after is a boxplot sorted by Mean but labelled by Entity. How can I achieve this?

Community
  • 1
  • 1
Ephemera
  • 8,672
  • 8
  • 44
  • 84

1 Answers1

2

Entity needs to be a factor with levels sorted in the right order:

df$Entity <- factor(df$Entity, levels = df$Entity[rank(df$Mean)])
Victor K.
  • 4,054
  • 3
  • 25
  • 38
  • Thanks, that's just what I was after. However, it doesn't work with duplicate Mean values, is there a way of automatically handling (without removing) duplicates? – Ephemera Jan 30 '13 at 05:49