How I can order the x-axis columns in descending order of percentages? By default, ggplot orders a discrete x-axis by the ordering of the categories of x
variable. For a character variable, the ordering will be alphabetic. For a factor variable, the ordering will be the ordering of the levels of the factor.
In my example, the levels of summary$variable
are as follows:
levels(summary$variable)
[1] "Q1" "Q2"
To reorder by pct
, one way would be with the reorder
function. Compare these (using the summary data frame from above):
summary$pct2 = summary$pct + c(0.3, -0.15, -0.45, -0.4, -0.1, -0.2, -0.15, -0.1)
ggplot(summary, aes(x=variable, y=pct2, fill=value)) +
geom_bar(position="stack", stat="identity") +
facet_grid(~Year)
ggplot(summary, aes(x=reorder(variable, pct2), y=pct2, fill=value)) +
geom_bar(position="stack", stat="identity") +
facet_grid(~Year)
Notice that in the second plot, the order of "Q1" and "Q2" has now reversed. However, notice in the left panel, the Q1 stack is taller while in the right panel, the Q2 stack is taller. With faceting you get the same x-axis ordering in each panel, with the order determined (as far as I can tell) by comparing the sum of all Q1 values and the sum of all Q2 values. The sum of Q2 is smaller, so they go first. The same happens when you use position="dodge"
, but I used "stack" to make it easier to see what's happening. The examples below will hopefully help clarify things.
# Fake data
values = c(4.5,1.5,2,1,2,4)
dat = data.frame(group1=rep(letters[1:3], 2), group2=LETTERS[1:6],
group3=rep(c("W","Z"),3), pct=values/sum(values))
levels(dat$group2)
[1] "A" "B" "C" "D" "E" "F"
# plot group2 in its factor order
ggplot(dat, aes(group2, pct)) +
geom_bar(stat="identity", position="stack", colour="red", lwd=1)
# plot group2, ordered by -pct
ggplot(dat, aes(reorder(group2, -pct), pct)) +
geom_bar(stat="identity", colour="red", lwd=1)
# plot group1 ordered by pct, with stacking
ggplot(dat, aes(reorder(group1, pct), pct)) +
geom_bar(stat="identity", position="stack", colour="red", lwd=1)
# Note that in the next two examples, the x-axis order is b, a, c,
# regardless of whether you use faceting
ggplot(dat, aes(reorder(group1, pct), pct)) +
geom_bar(stat="identity", position="stack", colour="red", lwd=1) +
facet_grid(.~group3)
ggplot(dat, aes(reorder(group1, pct), pct, fill=group3)) +
geom_bar(stat="identity", position="stack", colour="red", lwd=1)
For more on ordering axis values by setting factor orders, this blog post might be helpful.