Ed McMan
Ed McMan

Reputation: 529

Re-ordering by multi-dimensional data for ggplot2 plotting

I'm having some trouble producing what I think should be a fairly straightforward ggplot2 graph.

I have some experimental data in a data frame. Each data entry is identified by the system that was being measured, and the instance (problem) it was run on. Each entry also has a value measured for the particular system and instance.

For instance:

mydata <- data.frame(System=c("a","b","a","b","a","b"), Instance=factor(c(1,1,2,2,3,3)), Value=c(10,5,4,2,7,8))

Now, I'd like to plot this data in a boxplot where the x-axis contains the instance identifier, and the color of the bar indicates which system the value is for. The bar heights should be weighted by the value in the dataframe.

This almost does what I want:

qplot(data=mydata, weight=Value, Instance, fill=System, position="dodge")

The final thing that I would like to do is reorder the bars so they are sorted by the value of system A. However, I can't figure out an elegant way to do this.

My first instinct was to use qplot(data=mydata, weight=Value, reorder(Instance, Value), fill=System, position="dodge"), but this will order by the mean value for each instance, and I just want to use the value from A. I could use qplot(data=mydata, weight=Value, reorder(Instance, Value, function(x) { x[1] } ), fill=System, position="dodge") to order the instances by "the first value", but this is dangerous (what if the order changes?) and unclear to a reader.

What is a more elegant solution?

Upvotes: 0

Views: 275

Answers (1)

nograpes
nograpes

Reputation: 18323

I'm sure there is a better way than this, but making Instance an ordered works, and would continue to work even if the data changes:

qplot(data=mydata, weight=Value, 
 ordered(Instance,
 levels=mydata[System=='a','Instance'] [order(mydata[System=='a','Value'])])
,fill=System, position="dodge")

Perhaps a slightly more elegant way of writing the same thing:

qplot(data=mydata, weight=Value, 
ordered(Instance,
levels=Instance [System=='a'] [order(Value [System=='a'])]) # Corrected
,fill=System, position="dodge")

Upvotes: 3

Related Questions