4 回答

TA貢獻1824條經驗 獲得超5個贊
排序的關鍵是按所需順序設置因子的級別。不需要有序因子; 有序因子中的額外信息不是必需的,如果在任何統計模型中使用這些數據,可能會導致錯誤的參數化 - 多項式對比不適合這樣的標稱數據。
## 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)
條形圖
在最一般意義上,我們只需要將因子水平設置為所需的順序。如果未指定,則因子的級別將按字母順序排序。您也可以在上面的因子調用中指定級別順序,也可以采用其他方式。
theTable$Position <- factor(theTable$Position, levels = c(...))

TA貢獻1796條經驗 獲得超7個贊
@GavinSimpson:這reorder
是一個強大而有效的解決方案:
ggplot(theTable, aes(x=reorder(Position,Position, function(x)-length(x)))) + geom_bar()

TA貢獻2080條經驗 獲得超4個贊
使用scale_x_discrete (limits = ...)
指定的巴左右。
positions <- c("Goalkeeper", "Defense", "Striker")p <- ggplot(theTable, aes(x = Position)) + scale_x_discrete(limits = positions)

TA貢獻2011條經驗 獲得超2個贊
我認為已經提供的解決方案過于冗長。使用ggplot進行頻率排序條形圖的更簡潔方法是
ggplot(theTable, aes(x=reorder(Position, -table(Position)[Position]))) + geom_bar()
它與Alex Brown的建議相似,但有點短,無需任何函數定義。
更新
我認為我的舊解決方案當時很好,但是現在我寧愿使用forcats::fct_infreq
哪種方式按頻率排序因子水平:
require(forcats)ggplot(theTable, aes(fct_infreq(Position))) + geom_bar()
- 4 回答
- 0 關注
- 684 瀏覽
添加回答
舉報