亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在分類變量的圖表中顯示%而不是計數

在分類變量的圖表中顯示%而不是計數

DIEA 2019-07-02 09:40:08
在分類變量的圖表中顯示%而不是計數我正在繪制一個分類變量,而不是顯示每個類別值的計數。我在找方法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語法??偨Y上述評論中的討論:

 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


這個問題目前是谷歌最熱門的“gggketcount vs.persion直方圖”,因此希望這有助于提取當前包含在已接受答案的評論中的所有信息。

備注:如果hp不設置為一個因素,ggart返回:


查看完整回答
反對 回復 2019-07-02
?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

這個修改后的代碼應該可以工作。

p = ggplot(mydataf, aes(x = foo)) + 
    geom_bar(aes(y = (..count..)/sum(..count..))) + 
    scale_y_continuous(formatter = 'percent')

如果您的數據具有nas,并且不希望它們包含在繪圖中,則將na.omit(Mydataf)作為參數傳遞給ggart。

希望這能幫上忙。


查看完整回答
反對 回復 2019-07-02
?
jeck貓

TA貢獻1909條經驗 獲得超7個贊

對于ggplot 2版本2.1.0,它是

+ scale_y_continuous(labels = scales::percent)


查看完整回答
反對 回復 2019-07-02
  • 3 回答
  • 0 關注
  • 780 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號