Order Bars in ggplot2 bar graph Order Bars in ggplot2 bar graph r r

Order Bars in ggplot2 bar graph


@GavinSimpson: reorder is a powerful and effective solution for this:

ggplot(theTable,       aes(x=reorder(Position,Position,                     function(x)-length(x)))) +       geom_bar()


The key with ordering is to set the levels of the factor in the order you want. An ordered factor is not required; the extra information in an ordered factor isn't necessary and if these data are being used in any statistical model, the wrong parametrisation might result — polynomial contrasts aren't right for nominal data such as this.

## set the levels in order we wanttheTable <- within(theTable,                    Position <- factor(Position,                                       levels=names(sort(table(Position),                                                         decreasing=TRUE))))## plotggplot(theTable,aes(x=Position))+geom_bar(binwidth=1)

barplot figure

In the most general sense, we simply need to set the factor levels to be in the desired order. If left unspecified, the levels of a factor will be sorted alphabetically. You can also specify the level order within the call to factor as above, and other ways are possible as well.

theTable$Position <- factor(theTable$Position, levels = c(...))


Using scale_x_discrete (limits = ...) to specify the order of bars.

positions <- c("Goalkeeper", "Defense", "Striker")p <- ggplot(theTable, aes(x = Position)) + scale_x_discrete(limits = positions)