# 在ggplot2条形图中订单栏

``Name Position 1 James Goalkeeper 2 Frank Goalkeeper 3 Jean Defense 4 Steve Defense 5 John Defense 6 Tim Striker` `

` `p <- ggplot(theTable, aes(x = Position)) + geom_bar(binwidth = 1)` `

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

` `levels(theTable\$Position) <- c(...)` `

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

@GavinSimpson： `reorder`是一个强大而有效的解决scheme：

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

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

` `ggplot(theTable, aes(x=reorder(Position, -table(Position)[Position]))) + geom_bar()` `

` `require(forcats) ggplot(theTable, aes(fct_infreq(Position))) + geom_bar()` `

` `theTable <- transform( theTable, Position = ordered(Position, levels = names( sort(-table(Position)))))` `

（请注意， `table(Position)`生成`Position`列的频率计数。）

` `library(tidyverse) library(forcats) theTable <- data.frame( Name = c('James', 'Frank', 'Jean', 'Steve', 'John', 'Tim'), Position = c('Zoalkeeper', 'Zoalkeeper', 'Defense', 'Defense', 'Defense', 'Striker')) theTable %>% count(Position) %>% mutate(Position = fct_reorder(Position, n, .desc = TRUE)) %>% ggplot(aes(x = Position, y = n)) + geom_bar(stat = 'identity')` `

` `library(dplyr) #reorder the table and reset the factor to that ordering theTable %>% group_by(Position) %>% # calculate the counts summarize(counts = n()) %>% arrange(-counts) %>% # sort by counts mutate(Position = factor(Position, Position)) %>% # reset factor ggplot(aes(x=Position, y=counts)) + # plot geom_bar(stat="identity") # plot histogram` `

` `dplyr::count(theTable, Position) %>% arrange(-n) %>% mutate(Position = factor(Position, Position)) %>% ggplot(aes(x=Position, y=n)) + geom_bar(stat="identity")` `