如何在 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()
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
加载 scales 包并创建 Y 轴上具有百分比的条形图 -
示例
> library(scales) > ggplot(df,aes(x))+geom_bar(aes(y=(..count..)/sum(..count..)))+scale_y_continuous(labels =percent_format())
输出
广告