如何在 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())

輸出

更新於: 08-Sep-2020

2K+ 瀏覽

開啟你的職業生涯

完成課程即可獲得認證

立即開始
廣告
© . All rights reserved.