使用stack='identity'
繪製堆積條形圖時,我注意到堆棧的順序在每個條形圖中以不同的方式顯示。這是使用stat='bin'
的情節,就是ggplot計算每個類別的飛行元素數作圖之前(data.table
是有更高版本):如何使用stat ='identity'來保持ggplot中堆棧的順序?
library(ggplot2)
library(data.table)
diamonds <- data.table(diamonds)
ggplot(diamonds, aes(clarity, fill = cut)) + geom_bar(position="fill")
在每個酒吧,訂單'cut'的順序依次是因素的順序。不過,如果我繪製之前總結,並使用stat=identity
,這個訂單丟失:
diamonds_sum <- diamonds[, list(.N), by=list(cut, clarity)]
ggplot(diamonds_sum, aes(clarity, y=N, fill = cut)) + geom_bar(stat="identity", position="fill")
出現這種情況,儘管兩個表中級別的順序是一樣的:
levels(diamonds_sum$cut) == levels(diamonds$cut)
[1] TRUE TRUE TRUE TRUE TRUE
所以這個問題是雙重的:(i)爲什麼堆棧的順序不一樣?和(ii)如何解決這個問題?
這個簡單的解決方案當然是一直使用stat='bin'
,但是我的真實數據集有幾百萬條記錄,總結和繪圖速度更快。
非常好,謝謝!我錯誤地認爲ggplot並不關心行中元素的順序,只關心繪製元素的順序。活到老,學到老。 – fridaymeetssunday
@fridaymeetssunday呃,我其實也有這種印象。你的榜樣讓我意識到它確實很重要。 – Jaap