如何在 R 中使用 ggplot2 在 Y 軸上按照百分比建立條形圖?
通常,條形圖的 Y 軸使用頻率或計數建立,無論使用手動方式還是使用任何軟體或程式語言,但有時我們想要使用百分比。可以透過在 R 中使用 scales 包來實現,該包提供 labels=percent_format() 選項來將標籤更改為百分比。
示例
考慮以下資料框 -
> x<-sample(1:4,20,replace=TRUE) > df<-data.frame(x) > df
輸出
x 1 2 2 3 3 3 4 1 5 2 6 4 7 4 8 4 9 2 10 3 11 3 12 4 13 3 14 4 15 4 16 1 17 3 18 1 19 4 20 1
載入 ggplot2 包並建立條形圖 -
> library(ggplot2) > ggplot(df,aes(x))+geom_bar()
輸出

載入 scales 包並建立 Y 軸上具有百分比的條形圖 -
示例
> library(scales) > ggplot(df,aes(x))+geom_bar(aes(y=(..count..)/sum(..count..)))+scale_y_continuous(labels =percent_format())
輸出

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP