This question asks about ordering a bar graph according to an unsummarized table. I have a slightly different situation. Here\'s part of my original data:
ex
It's all in making
pvs_id
a factor and supplying the appropriate levels to it:
dat$pvs_id <- factor(dat$pvs_id, levels = dat[order(-dat$mqs), 2])
m = melt(dat, id.var="pvs_id", measure.var=c("mqs","imcs"))
ggplot(m, aes(x=pvs_id, y=value))+
geom_bar(aes(fill=variable), position="dodge", stat="identity")
This produces the following plot:
EDIT:
Well since pvs_id
was numeric it is treated in an ordered fashion. Where as if you have a factor no order is assumed. So even though you have numeric labels pvs_id
is actually a factor (nominal). And as far as dat[order(-dat$mqs), 2]
is concerned the order function with a negative sign orders the data frame from largest to smallest along the variable mqs
. But you're interested in that order for the pvs_id
variable so you index that column which is the second column. If you tear that apart you'll see it gives you:
> dat[order(-dat$mqs), 2]
[1] 6 2 0 5 7 4 8 3 1
Now you supply that to the levels
argument of factor
and this orders the factor as you want it.