Reputation: 345
I have a dataframe with more than one factor, for example:
df <- data.frame(foo = factor(c("joe", "jack", "jane", "jim")),
bar = factor(c("A", "B", "A", "B")),
baz = c(8, 3, 9, 9))
Now I want to get a barplot, but not in the alphabetical order of the "foo" factor, but orderd by the "bar" factor.
ggplot(df, aes(x = foo, y = baz, fill = bar)) +
geom_bar(stat="identity")
will plot only ordered by the "foo" factor alphabetically. Also, can I order by a factor that is not even used by ggplot? For example if I had a third factor in the df dataframe?
Bonus question: Are there good tutorials on ordering factors? Every time I have to do this (for ggplot) I have to Google it and always get confused.
Upvotes: 0
Views: 98
Reputation: 74
ggplot(df, aes(x = factor(foo, levels=foo[order(bar)]), y = baz)) +
geom_bar(stat="identity")
Upvotes: 1