1

I am working on stack barchart and here is the test code :

dat <- read.table(text="
cars    trucks  suvs
10   40   25
20   20   35
30   15   25
50   25   30
20   30  15", header=TRUE, as.is=TRUE)
dat$day <- factor(c("Mo", "Tu", "We", "Th", "Fr"), 
                  levels=c("Mo", "Tu", "We", "Th", "Fr"))

library(reshape2)
library(ggplot2)

mdat <- melt(dat, id.vars="day")
head(mdat)
ggplot(mdat, aes(variable, value, fill=day)) + 
  geom_bar(stat="identity", position="stack")+coord_flip()

What I want is : i would like to know if i can change the order of the group factors (dat$day) for each variable in the plot. The goal is to have the same barchart with different order color for each variable. Changing the color order is not hard but different order is a different story. Indeed, i want to have the first color assign to the biggest value for each variable.

i hope i was enough specific. Thanks in advance.

Sandy Muspratt
  • 31,719
  • 12
  • 116
  • 122
william
  • 13
  • 3

1 Answers1

2

What comes to my mind immediately is the arrange function from dplyr (which essentially does nothing but to order a dataframe - "Arrange rows by variables."):

ggplot(arrange(mdat,variable,desc(value)), aes(variable, value, fill=day)) + 
    geom_bar(stat="identity", position="stack")+coord_flip()

plot

maj
  • 2,479
  • 1
  • 19
  • 25
  • Frankly, I think your question is *quite* a duplicate: All you want is ordering, right? In that case, there are already questions like this, for example (you might want to consider reading this as there are solutions in it that do *not even* need the dplyr package): http://stackoverflow.com/questions/1296646/how-to-sort-a-dataframe-by-columns-in-r , http://stackoverflow.com/questions/7793295/in-r-how-to-order-a-data-frame-by-one-descending-and-one-ascending-column – maj May 21 '15 at 09:42
  • And this one might help as well, even though it uses qplot: http://stackoverflow.com/questions/2427742/how-do-i-change-the-stacking-order-in-a-bar-chart-in-ggplot2 – maj May 21 '15 at 10:01
  • If an answer gives you "exactly what [you] want", please make sure to accept it! – maj May 22 '15 at 14:28