在分類變量的圖表中顯示%而不是計數我正在繪制一個分類變量,而不是顯示每個類別值的計數。我在找方法ggplot若要顯示該類別中值的百分比,請執行以下操作。當然,用計算出的百分比和繪圖來創建另一個變量是可能的,但是我必須做幾十次,我希望能在一個命令中實現這一點。我在做這樣的實驗qplot(mydataf) +
stat_bin(aes(n = nrow(mydataf), y = ..count../n)) +
scale_y_continuous(formatter = "percent")但我一定是不正確地使用它,因為我有錯誤。為了方便地再現設置,下面是一個簡化的示例:mydata <- c ("aa", "bb", NULL, "bb", "cc", "aa", "aa", "aa", "ee", NULL, "cc");mydataf <- factor(mydata);qplot (mydataf); #this shows the count, I'm looking to see % displayed.在實際情況下,我可能會用ggplot而不是qplot,但是正確的使用方式統計箱我還是逃避不了。我也嘗試過以下四種方法:ggplot(mydataf, aes(y = (..count..)/sum(..count..))) +
scale_y_continuous(formatter = 'percent');ggplot(mydataf, aes(y = (..count..)/sum(..count..))) +
scale_y_continuous(formatter = 'percent') + geom_bar();ggplot(mydataf, aes(x = levels(mydataf), y = (..count..)/sum(..count..))) +
scale_y_continuous(formatter = 'percent');ggplot(mydataf, aes(x = levels(mydataf), y = (..count..)/sum(..count..))) +
scale_y_continuous(formatter = 'percent') + geom_bar();但所有4項都給予:Error: ggplot2 doesn't know how to deal with data of class factor簡單的情況下,也會出現相同的錯誤。ggplot (data=mydataf, aes(levels(mydataf))) +
geom_bar()所以很明顯是關于ggplot與單個向量相互作用。我在抓我的頭,在谷歌上搜索那個錯誤給了我一個結果.
3 回答

MM們
TA貢獻1886條經驗 獲得超2個贊
ggplot
require(ggplot2) require(scales) p <- ggplot(mydataf, aes(x = foo)) + geom_bar(aes(y = (..count..)/sum(..count..))) + ## version 3.0.0 scale_y_continuous(labels=percent)
mtcars
:
ggplot(mtcars, aes(x = factor(hp))) + geom_bar(aes(y = (..count..)/sum(..count..))) + scale_y_continuous(labels = percent) ## version 3.0.0
備注:hp

蝴蝶刀刀
TA貢獻1801條經驗 獲得超8個贊
p = ggplot(mydataf, aes(x = foo)) + geom_bar(aes(y = (..count..)/sum(..count..))) + scale_y_continuous(formatter = 'percent')
- 3 回答
- 0 關注
- 780 瀏覽
添加回答
舉報
0/150
提交
取消