0

The code below is supposed to loop over 11 rows of data in a data.frame, take the means of subsets of each row, and then bar chart the means of each row's subsets against the day of the week. When it makes these bar charts, each mean is correctly plotted with the right day of the week, but the bars are ordered alphabetically instead of in the order the data was presented. Why is that and how can it be fixed?

dailyData[1] <- lapply(dailyData[1], function(x) (x-2)%%7 + 1)
data <- vector(mode="numeric", length=7)
dotw <- weekdays(x=as.Date(seq(7), origin="1950-01-01"))
for(i in 0:10){
    for(day in 1:7){
        ss <- subset(dailyData, DOTY == day)
        data[day] <- sum(ss[[i+2]])/length(ss[[i+2]])
}
df <- data.frame(data)
myplot <- ggplot(df, aes(y=df[[1]], x=dotw))
myplot + geom_bar(stat="identity") + xlab("Day Of The Week") + ylab("Mean Hourly Usage") + ggtitle(paste("The effects of DOTW on usage for customer", i, "in 2012", sep=" "))
ggsave(filename=paste("C:\\SCRATCHDIR\\Plots\\DOTW\\", i, ".jpg", sep=""))
}
  • 1
    [How to make a great R reproducible example?](http://stackoverflow.com/questions/5963269) – zx8754 Jul 21 '16 at 19:03
  • Just guessing, check str() of your data, x might be a factor. – zx8754 Jul 21 '16 at 19:04
  • Edited to ask a unique question – Henry Prickett-Morgan Jul 21 '16 at 19:16
  • Is it plotting in alphabetical order or random order? Can you *Edit* the question, remove some of the unneeded text, and clearly state the problem? – jww Jul 21 '16 at 21:14
  • Don't see how this is a unique question (or reproducible, but that doesn't matter so much as the problem is clearly a dupe). Factors will default to alphabetical order. ggplot will coerce strings to factors. If you want a non-alphabetical order you need to specify it with `factor(..., levels = c())`, or `reorder` if it you want is based on a numeric column. – Gregor Thomas Jul 22 '16 at 17:01
  • Since this case isn't odering based on a numeric, perhaps [How do you specifically order ggplot2 x axis instead of alphabetical order?](http://stackoverflow.com/q/12774210/903061) would be a better dupe. – Gregor Thomas Jul 22 '16 at 17:05
  • Thanks Gregor, that worked perfectly. – Henry Prickett-Morgan Jul 22 '16 at 17:45

0 Answers0